0

I'm building a 'scrabble' game in Python. Basically, the user is given 7 randomly generated letters and these are stored in the list random_letters. They then enter a word using those letters - this is a string stored as player1_word.

The bit I am stuck on is where I need to validate that the user has entered a valid word - e.g is player1_word only using letters from random_letters.

def is_valid_answer(player_word: str, letters: list) -> bool:
    ...

Expected behaviour:

>>> random_letters = ["D", "O", "G", "P", "X", "K"]
>>> is_valid_answer("DOG", random_letters)
True
>>> is_valid_answer("CAT", random_letters)
False
gz.
  • 6,661
  • 1
  • 23
  • 34
sf318
  • 13
  • 2

3 Answers3

0
randomLetters = [ 'a' , 'b' , 'x']

word = input('Enter A word : ')
first_letter = word[0]
if first_letter in randomLetters:
  print('valid')
else:
  print('Not valid')

RESULT

Enter A word :  alex
valid

Enter A word :  devon
Not valid
Fuji Komalan
  • 1,979
  • 16
  • 25
0

You can use set operation to do this:

if not set(Player1Word) - set(randomLetters):
    print "Valid"

set is a data structure contains only unique items. The idea is, convert both of them set. And, then subtract randomLetters from Player1Word to see if Player1Word contains something that not in randomLetters. If it doesn't contain, the Player1Word is valid, otherwise not.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • Thanks, this worked perfectly, just what I was looking for. Never knew about 'set' before, never come across it. Many thanks ;) – sf318 May 07 '17 at 15:27
  • There is a subtle problem with this answer. For instance, if I am given the letters A,E,O,D,T,W,X and provide the answer WOOD, your code will report my answer as valid when it is not. – gz. May 07 '17 at 22:12
  • @gz. Indeed it does, good spot. My bad for not testing thoroughly! Any ideas on how to fix this? – sf318 May 13 '17 at 15:39
  • @sf318 was giving others a chance to fix/answer, but have posted a solution now. – gz. May 13 '17 at 16:22
0

Python does not have a native multiset type so there's not quite a one-liner for this, but collections.Counter helps a little:

def is_valid_answer(word, letters):
    letter_counts = collections.Counter(letters)
    for letter in word:
        if not letter_counts[letter]:
            return False
        letter_counts[letter] -= 1
    return True

Using Counter at least saves you the loop you'd need to populate a plain dict with the counts.

Community
  • 1
  • 1
gz.
  • 6,661
  • 1
  • 23
  • 34