I am trying to make this code alternate between setting i as 56 and i as 0 I cant seem to get the second if statement to trigger. The first one works.
while True:
print 'is55 before if logic is' + str(is56)
if is56 == True:
i = 0
is56 = False
#print 'true statement' + str(i)
print 'True is56 statement boolean is ' + str(is56)
if is56 == False:
i = 56
is56 = True
print 'i is ' + str(i)
You have two separate if, so you enter the first one, set is56 to False, and then immediately enter the second one and set it back to True. Instead, you could use an else clause:
while True:
print 'is55 before if logic is' + str(is56)
if is56:
i = 0
is56 = False
else: # Here!
i = 56
is56 = True
print 'i is ' + str(i)
any objections ?
while True:
print 'is55 before if logic is' + str(is56)
i = is56 = 0 if is56 else 56
print 'i is ' + str(i)
The changes in the first if block are immediately reversed by the next one.
You want to replace the separate if blocks with a single if/else block.
On another note, you could simply use an itertools.cycle object to implement this:
from itertools import cycle
c = cycle([0, 56])
while True:
i = next(c)
print 'i is ' + str(i)
# some code
Without an elif, the original code, if working, would execute both blocks. Why not:
def print_i(i):
print 'i is ' + str(i)
while True:
print_i(56)
print_i(0)
Related
I am trying to make a function that automatically generated a response to a selection of an action in a text adventure game. My problem is that I have to replace every second '_' with ' '. However I have tried everything I have though of and whenever I google the question the only solution I get is to use .replace(). However .replace() replaces every instance of that character. Here is my code, could you please fix this for me and explain how you fixed it.
example_actions = ['[1] Search desk', '[2] Search Cupboard', '[3] Search yard'
def response(avaliable_actions):
for i in avaliable_actions:
print(i, end=' ')
x = avaliable_actions.index(i)
avaliable_actions[x] = avaliable_actions[x][4:]
avaliable_actions = ' '.join(avaliable_actions)
avaliable_actions = avaliable_actions.lower()
avaliable_actions = avaliable_actions.replace(' ', '_')
avaliable_actions = list(avaliable_actions)
count = 0
for i in avaliable_actions:
if count == 2:
count = 0
index = avaliable_actions.index(i)
avaliable_actions[index] = ' '
elif i == '_':
count += 1
avaliable_actions = ' '.join(avaliable_actions)
print('\n\n' + str(avaliable_actions)) #error checking
Here's one approach:
s = 'here_is_an_example_of_a_sentence'
tokens = s.split('_')
result = ' '.join('_'.join(tokens[i:i+2]) for i in range(0,len(tokens),2))
print(result)
The result:
here_is an_example of_a sentence
Did I understand you correct, that you wanna produce something like this?
this_is_a_test -> this is_a test or this_is a_test?
If so, adapt the following for your needs:
s = "this_is_just_a_test"
def replace_every_nth_char(string, char, replace, n):
parts = string.split(char)
result = ""
for i, part in enumerate(parts):
result += part
if i % n == 0:
result += replace
else:
result += char
return ''.join(result)
res = replace_every_nth_char(s, "_", " ", 2)
print(s, "->", res)
# "this_is_just_a_test" -> "this is_just a_test"
I have a function in which I need to inject a character before every odd index of a string.
def inject(s, i):
sent = str(s)
new = []
for w in sent:
if w == ' ':
new.append(w)
elif (sent.index(w) % 2 == 1):
new.append(str(i) + w)
else:
new.append(w)
return ''.join(new)
The function works for:
inject(1339, 3)
output: '1333339'
and works for
inject('This is a test', 'x')
output: 'Txhixs ixs a txexst'
but won't work for:
inject('Hello World', 'x')
output: 'Hxello World'
I know it has something to do with it breaking on the 'll' but can't figure out how to fix it.
Thanks!
I think you meant to do this:
def inject(s, i):
sent = str(s)
new = []
for idx,w in enumerate(sent):
if w == ' ':
new.append(w)
elif idx % 2 == 1:
new.append(str(i) + w)
else:
new.append(w)
return ''.join(new)
for t in [1339, 'This is a test', 'Hello World']:
print(t, inject(t,'x'))
When using the enumerate() you get the index of each character without having to search for it.
The sent.index(w) call just doesn't do what you want it to even though it might seem like it does when there are no repeated characters in a string.
I have the following code which helps to bruteforce hashes
The first if statement will run, the values are hash=wordlist.txt, args=abtfg, values=[0, "0,1", 0, wordlist.txt, true]
def bruteforce(hash, args, values):
if "." in hash:
files = open(values[args.find("f")]) # Open wordlist.txt
for xhsd in files.readlines():
hash = xhsd
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet += alphabet.upper() + "0123456789!$%^&*(){}~#][;:'#/?.>,<"
if "b" in args: # It is
m = args.find("b")
m = values[m]
else:
m = "0,16"
# m is 0,10
start_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
l = 0
print("Cracking...")
attempts = 0
while l == 0:
password = ""
for x in range(random.randrange(int(m.split(",")[0])+1,int(m.split(",")[1])+1)): # range(random.randrange(0,10))
password += alphabet[random.randrange(0,len(alphabet)-1)]
num = hash_types[int(values[args.find("t")])] # num="md5"
htype = "hash2 = hashlib."+num+"(password).hexdigest()"
exec(htype) # hash2 = md5(password)
print hash2 + ":" + hash # Compares the hashes
if hash == hash2:
print password
l = 1
else:
print "Trying..."
The first item it tries, it cracks it almost instantly, printing:
0cc175b9c0f1b6a831c399e269772661:0cc175b9c0f1b6a831c399e269772661
(this is hash2 and hash). So we now know these two variables are equal. However, the if statement directly below it, doesn't run. This is the weirdest thing I've seen in Python, could anyone explain why this is? I've printed both variables and they're clearly the same...
Removing whitespace could help:
if hash.strip() == hash2.strip():
I wrote some code but I can't get why the pyscripter is telling a syntax error in the if statement:
#search for 9 elements
file_writer = open('C:\\PythonProject2\\commands_NUM.txt','w')
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag = True:###ERROR
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##Here is the syntax error
file_writer.close()
def search_object(pixel,frame,min_val,max_val):
(obj_y,obj_x) = pixel
y_center = pixel[0]+1
x_center = pixel[1]+1
if(obj_y<=597 and obj_x<=797 ):
for y in range(0,3):
for x in range(0,3):
if((frame[obj_y+y][obj_x+x])<=min_val or(frame[obj_y+y] [obj_x+x])>=max_val ):
return False
return True
if statement is indented inwards in for loop. And also = means assignment use == instead
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag == True: #here indent this if one step back
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##He
there should be == in if statement
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag == True:
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n')
1) Put your search_object function above - declare it before using it.
2) Fix if flag = True: to if flag:
3) Fix file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') line indentation.
4) return True inside the function search_object is with wrong indentation too. Fix it.
I would recommend you to look at PEP 8.
I'm trying to write a function that will translate the input into so-called "cow Latin." I want to return the values from the if statement but whenever I do I get a syntax error. I can print the value but I want to avoid the function returning None as well.
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
print('{0}moo'.format(cow_word), end=' ')
else:
cow_word = sentence_list[i][1:] + sentence_list[i][:1]
print('{0}oo'.format(cow_word), end=' ')
cow_latin = cow_latinify_sentence("the quick red fox")
print(cow_latin)
In short, how can I get the function to return instead of print?
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += ('{0}moo'.format(cow_word) + ' ')
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()
>>> cow_latinify_sentence('hello there i am a fish')
'ellohoo heretoo imoo ammoo amoo ishfoo'
Why not just replace the two instances of
print('{0}moo'.format(cow_word), end=' ')
with
return '{0}moo'.format(cow_word)+' '
You have to get rid of end=; you don't have to replace the newline that would otherwise follow the output of print, but if you want a space at the end of the returned string you still have to append it yourself.
You need to create a list to accumulate your results.
result = []
your two print statements in your function would need changed to result.append(XXXX). Then when you have processed the entire sentence you can
return (result)
or, to re-form it into a sentence:
return " ".join(result) + '.'
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += '{0}moo'.format(cow_word) + ' '
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()