query level: beginner
As part of a learning exercise I have written code that must check if a string (as it is build up through raw_input) matches the beginning of any list item and if it equals any list item.
wordlist = ['hello', 'bye']
handlist = []
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
for item in wordlist:
if item.startswith(hand):
while item.startswith(hand):
if hand not in wordlist:
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
else: break
else: break
print 'you loose'
This code works but how can my code (and my reasoning/approach) be improved?
I have the feeling that my nesting of IF, WHILE and FOR statements is overkill.
EDIT
Thanks to Dave, I was able to considerably shorten and optimise my code.
wordlist = ['hello','hamburger', 'bye', 'cello']
hand = ''
while any(item.startswith(hand) for item in wordlist):
if hand not in wordlist:
hand += raw_input('enter letter: ')
else: break
print 'you loose'
I’m surprised my original code worked at all…
Firstly, you don’t need the
handlistvariable; you can just concatenate the value ofraw_inputwithhand.You can save the first
raw_inputby starting thewhileloop withhandas an empty string since every string hasstartswith("")asTrue.Finally, we need work out best way to see if any of the items in
wordliststarts withhand. We could use a list comprehension for this:and then check the length of the returned list if greater than zero.
However, even better, python has the
any()function which is perfect for this: it returnsTrueif any element of an iterable isTrue, so we just evaluatestartswith()for each member ofwordlist.Putting this all together we get: