Function that determines if all the letters contained in a string are in the other

1
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
    '''
    certas =0
    for i in range(len(secretWord)):
        if secretWord[i] in lettersGuessed:
            certas += 1

    #print(certas)

    if certas == len(secretWord):
        return True


    else:
        return False

secretWord = 'durian' 
#lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
#lettersGuessed = ['e', 'a', 'l', 'p', 'e']
#isWordGuessed('durian', ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u'])
lettersGuessed = ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u']
print(isWordGuessed(secretWord, lettersGuessed))

Objective is to determine if all the letters of secretWord are contained in lettersGuessed .

My code is working. Is there any way Pythonica does?

    
asked by anonymous 22.04.2018 / 20:15

2 answers

3

You can do it in a line:

def is_word_guessed(secret_word, letters_guessed):
     return all([letter in letters_guessed for letter in secret_word])

print(is_word_guessed('abcd',  ['a', 'b', 'd', 'c']))  # True

print(is_word_guessed('abcd',  ['a', 'b', 'e', 'c']))  # False

The function all returns True if all values in the list passed to it are True, and False if one or more of the values is False.

List understanding parses each letter in secret_word and adds a True element if the parsed letter is in letters_guessed and False if not.

    
22.04.2018 / 20:39
2

Another way to do it:

def isWordGuessed(secretWord, lettersGuessed):
    return set(secretWord).issubset(set(lettersGuessed))

The advantage I see in this case is to save the check for repeated characters.

See for example:

secretWord = 'aaaabcdddefg'
lettersGuessed = 'abcdefg'

When using all() , you are traversing secretWord 12 times and lettersGuessed up to 7 times for each of these 12. (This is a simple case of a few characters and where the strings are sorted).

    
26.04.2018 / 16:39