Home > Net >  defining a fuction using the for loop / Python
defining a fuction using the for loop / Python

Time:07-16

I need to define a function using the for loop. it's purpose is to check whether a letter included in secret_word is already included in the old_letters_guessed list. if it is, the function returns True. else, False. This is what I wrote thus far:

def check_win(secret_word, old_letters_guessed):
   for letter in old_letters_guessed or secret_word:
    if (secret_word.count(letter) > old_letters_guessed.count(letter)) and (old_letters_guessed.count(letter) == 0) or (secret_word.count(letter) > 0) and (old_letters_guessed.count(letter) == 0):
     return False
    else:
     return True

It works fine in these scenarios:

check_win('typewriter',['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'])

True

check_win('typewriter',[])

False

check_win('',['q'])

True

but in here, instead of returning False, its returning True:

check_win('typewriter',['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o'])

True

I've tried altering it many times without succeess and would appreciate your help.

Thank you very much!

CodePudding user response:

You can use this:

def check_win(word, guessed):
    for letter in word:
        if letter not in guessed:
            return False
    return True

print(check_win('typewriter', ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'])) # True
print(check_win('typewriter', [])) # False
print(check_win('', ['q'])) # True
print(check_win('typewriter', ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o'])) # False

What is happening in your code is it is returning something in the first iteration, rendering the for loop useless.

CodePudding user response:

Redefine the function:

try it out:

def check_win(secret_word, old_letters_guessed):
    for letter in old_letters_guessed:
        yield letter in secret_word     # same as: if letter in secret_word: yield True, else: yield False

secret = "typewriter"
old = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']

calling this "yielding-function" does not work the way functions usually do, because its a generator

print(check_win(secret,old))
returns <generator object check_win at 0x0000020BFF8480B0>

instantiate generator object:

mygenerator = check_win(secret,old)
n = 0
for i in mygenerator:
    print(f"{old[n]} is in {secret}: {i}")
    n  = 1
returns:
>>> q is in typewriter: False
>>> w is in typewriter: True
>>> e is in typewriter: True
>>> r is in typewriter: True
>>> t is in typewriter: True
>>> y is in typewriter: True
>>> u is in typewriter: False
>>> i is in typewriter: True
>>> o is in typewriter: False
>>> p is in typewriter: True

Once this works properly, you can think of ways to count the matches. Hope this helps.

  • Related