I'm making a word game in which the user has to guess a synonym of a word given the word and the length of the desired synonym. I have a dictionary with values of lists for each key where the keys are the words and the lists are their synonyms:
dictionary = {'method': ['mode', 'way', 'approach', 'arrangement', 'mechanism'], 'swiftly': ['speedily', 'promptly', 'quickly', 'hastily', 'rapidly'], 'laugh': ['chuckle', 'giggle', 'cackle', 'guffaw']}
I have it so that Python is selecting a word at random and then selecting one of that word's synonyms at random to have the user guess. However, if a word/key in the dictionary has synonyms/values with the same number of letters, it’s obviously only looking for one of them. So, if the user gives a different one, it will print “Incorrect.” even though it's technically correct, it’s just not the one it was looking for.
Is there an easy way to fix it so that it prints “Correct!” if the user inputs any of the synonyms of the given length for the randomly chosen word?
This is what I have:
def play_game():
word = random.choice(list(dictionary.keys()))
synonym = random.choice(dictionary[word])
guess = input("Guess a synonym for the word '" word "' that has " str(len(synonym)) " letters. \n")
if guess == synonym:
print("Correct!")
else:
print("Incorrect.")
CodePudding user response:
Store the length of the correct answer, rather than the word itself. Then, check whether the guess matches the desired length and is in the list of synonyms:
def play_game():
word = random.choice(list(dictionary.keys()))
length = len(random.choice(dictionary[word]))
guess = input("Guess a synonym for the word '" word "' that has " str(length) " letters. \n")
if len(guess) == length and guess in dictionary[word]:
print("Correct!")
else:
print("Incorrect.")
CodePudding user response:
Could you do something like this?
import random
def play_game():
word_to_synonym = {
"method": ["mode", "way", "approach", "arrangement", "mechanism"],
"swiftly": ["speedily", "promptly", "quickly", "hastily", "rapidly"],
"laugh": ["chuckle", "giggle", "cackle", "guffaw"],
}
random_word = random.choice(list(word_to_synonym.keys()))
random_synonym = random.choice(word_to_synonym[random_word])
random_synonym_length = len(random_synonym)
user_guess = input(
f"Guess a synonym for the word '{random_word}' that has {random_synonym_length} letters. \n"
).lower()
if user_guess in word_to_synonym[random_word]:
print("Correct!")
else:
print("Incorrect.")