views:

92

answers:

1

Hi

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 can my code (and my reasoning/approach) be improved? i have the feeling that my nesting of IF, WHILE and FOR statements is overkill?

thanks

Baba

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 orignal code worked at all...

+7  A: 

Firstly, you don't need the handlist variable; you can just concatenate the value of raw_input with hand.

You can save the first raw_input by starting the while loop with hand as an empty string since every string has startswith("") as True.

Finally, we need work out best way to see if any of the items in wordlist starts with hand. We could use a list comprehension for this:

[item for item in wordlist if item.startswith(hand)]

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 returns True if any element of an iterable is True, so we just evaluate startswith() for each member of wordlist.

Putting this all together we get:

wordlist = ['hello', 'bye'] 
hand = ""

while any(item.startswith(hand) for item in wordlist):
    hand += raw_input('enter letter: ')  
print 'you loose' 
Dave Webb
+1 for any. Didn't know that. (*learn something new today* - check)
Space_C0wb0y
@Space_C0wb0y - there's `all()` too: http://docs.python.org/library/functions.html#all
Dave Webb
@Dave Webb: I'll spare that one for tomorrow :)
Space_C0wb0y
Hi Dave. That's great thanks! So strings, just like lists, dictionaries and tuples, can also be populated. and it makes the "".join() part redundant. Thank You! I will rework my code and post it to see if it's any good. Although you're pretty close to what i had.
Baba