Home > Mobile >  Hangman game function to determine whether the user has won or not in Python
Hangman game function to determine whether the user has won or not in Python

Time:04-07

I'm trying to make hangman game. And this is the code I thought would work to check whether the game is won or not.

def is_word_guessed(secret_word, letters_guessed):
for char in secret_word:
    if char in letters_guessed:
        return True
    else:
        return False

word = 'apple'
list = ['a', 'e', 'l']

print(is_word_guessed(word, list))

But clearly it gives True even when only one character is guessed correctly. Also, how to make sure that when a user guesses 'p' once, (i.e. list = ['a','e','l','p']) the function does NOT return True? (i.e. two p's are required in the list to win)

Sorry for wasting your time in such stupid question but I could really use some help. Thank you!

CodePudding user response:

Let's think about what your function needs to do in order to work. Your function is_word_guessed(secret_word, letters_guessed) needs to return True if and only if every letter in secret_word exists within the letters_guessed array.

Let's write a brute force solution for this first. In this solution, we're going to loop through every character in secret_word and check if it exists within the letters-guessed array. If, after looping through, every character is in there we can return True, otherwise, if we find a character not in there, we return False.

for char in secret_word:
    if char not in letters_guessed:
        return False
return True

This solution will work, however, the "in" operator on a list in Python is O(n).

A Set is O(n) worst case (https://wiki.python.org/moin/TimeComplexity), but O(1) most of the time. So if you use a set, more likely than not you'll have a better performing check.

word = 'apple'
guesses = {'a', 'e', 'l'}

print(is_word_guessed(word, guesses))

CodePudding user response:

You could make a simple test with:

return all([x in letters_guessed for x in secret_word ])

This will return True if all the letters in the secret_word is present in the letters_guessed.

  • Related