0

So, lets say I have a secretWord = 'apple' and I have a list called lettersGuessed.

lettersGuessed = ['a', 'e', 'i', 'k', 'p', 'r', 's']

This function returns a boolean - True if secretWord has been guessed (ie, all the letters of secretWord are in lettersGuessed) and False otherwise.

And If I write something like this

for c in secretWord:
    matched = [l for l in lettersGuessed if c == l]
    if len(matched) == 0:
        return False

    return True

What exactly is happening in matched = [l for l in lettersGuessed if c == l]

1
  • 1
    open a python interpreter and you could see it for yourself, knowing what happens but why that is another question. Commented Jan 24, 2015 at 23:10

2 Answers 2

3

You're building a list of all the letters in the list that equal the current character of the secret word, and if that list is empty you deduce that current character hasn't been guessed yet.

Much simpler of course would be

return all(c in lettersGuessed for c in secretWord)

which, it seems to me, is also more immediately clear to the reader.

Sign up to request clarification or add additional context in comments.

Comments

0
matched = [l for l in lettersGuessed if c == l]

c is every letter in secretWord, and l is every letter in lettersGuessed. Lets check it part by part;

l for l in lettersGuessed 

This is equal to;

for l in lettersGuessed:
    dosomethingwith l

So this part returns l, other part is checking if c == l, so returns True if this True. Basically, if l matches with c.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.