L. John
L. John

Reputation: 39

How and when does the program reach "return True"?

Here is the code (an assignment), this code is correct, however I played around with it and got it on my second try, but I don't know if my understanding is correct:

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    # FILL IN YOUR CODE HERE...
    for i in secretWord:
        if i not in lettersGuessed:
            return False
    return True

So, if the return True was outside the loop, it would only return True if every single letter in secretWord was in there, but if one letter was missing, it would return False instantly. Is this correct?

Thanks!

Upvotes: 0

Views: 59

Answers (1)

Adam Smith
Adam Smith

Reputation: 54193

Right -- this is equivalent to:

all(lett in lettersguessed for lett in secretword)

Note that since membership tests of lists (or strings) are O(n), it can be faster if you have a comparatively larger secretword than lettersguessed to do:

def is_word_guessed(secretword, lettersguessed):
    guessed_set = set(lettersguessed)
    return all(lett in guessed_set for lett in secretword)

This is because testing membership in a set is done in constant time (O(1)), so the cost of constructing the set is outweighed by the many calls to membership check.

As usual in these sorts of edge optimizations -- profiling is highly recommended before making any change.

Upvotes: 1

Related Questions