dg123
dg123

Reputation: 65

Returning characters in single string lists

I'm not quite sure why this doesn't work, can anyone please help me fix this?

def valid(user_guess, valid_characters, guess_size):
    '''(list, str, int) -> bool
       Given a list of single character strS and a str, 
       return True if every character is in the given string.
     >>> (['A', 'C', 'B', 'E'], 'ACBE', 4)
     True
     >>> (['A', 'C', 'B', 'E'], 'ADFG', 4)
     False
    '''
    for char in user_guess:
        if char in valid_characters and len(user_guess) == guess_size:
            return True
        if char not in valid_characters and len(user_guess) != guess_size:
            return Fal

Upvotes: 0

Views: 130

Answers (4)

AGN Gazer
AGN Gazer

Reputation: 8378

I am not sure exactly how you want this code to work. However, based on your comment:

Given a list of single character strS and a str, return True if every character is in the given string.

I assume you simply want to know that all characters (="every character") in user_guess are in valid_characters. I would do it this way:

return len(set(user_guess).difference(valid_characters)) == 0

It is not clear what guess_size is supposed to do.

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60944

Here's a slightly more Pythonic way using all

def valid(user_guess, valid_characters, guess_size):
    return len(user_guess) == guess_size and all(c in valid_characters for c in user_guess)

Upvotes: 2

Supreet Sethi
Supreet Sethi

Reputation: 1806

This is one of many possible ways to valid the guesses

guesses = [(['A', 'C', 'B', 'E'], 'ACBE', 4),
           (['A', 'C', 'B', 'E'], 'ADFG', 4)]

def checkguess(g):
    chars = g[0]
    valid = g[1]
    guess_size = g[2]
    if chars == list(valid) and len(chars) == guess_size:
        return True
    else: 
        return False

if __name__ == '__main__':
    result = [checkguess(g) for g in guesses]
    assert result == [True, False]  

Upvotes: -1

DomJack
DomJack

Reputation: 4183

If the len(user_guess) == guess_size condition is satisfied the return True is triggering after only checking the first char. For correctness, return False when this condition fails, and return True outside the loop if this never triggers.

Also, the length condition doesn't need to be evaluated inside the loop.

Upvotes: 1

Related Questions