Elliot Tregoning Elliot Tregoning - 1 year ago 81
Python Question

Word guessing game -- Can this be written any better?

This is just a portion of the game, a function that takes in the secret word and the letters guessed as arguments and tells you if they guessed the word correctly.

I'll be completely honest, this is from an assignment on an edX course, however I have already passed this assignment, this code works. I am just wondering if it can be written any better. Some people in the discussion forums were talking about how they solved it with 1 line, which is why I'm asking.

def isWordGuessed(secretWord, lettersGuessed):
guessed = []
l= str(lettersGuessed)
s= list(secretWord)
for i in l:
if i in s:
return guessed == s

Here is one of the test cases from the grader as an example:

isWordGuessed('durian', ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u'])

Answer Source

Something like this is pretty short:

def isWordGuessed(secretWord, lettersGuessed):
  return all([c in lettersGuessed for c in secretWord])

For every character in the secretWord ensure it's in the lettersGuessed. This basically creates a list of booleans and the built-in all returns True if every element in the array is True.

Also, FWIW: Idiomatic python would use underscores and not camel case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download