Function to compare words to solve word game in Python

127 Views Asked by At

Im trying to find/write a function to compare two words in a Python program that solves a word puzzle game. The goal of the game is to create as many word as possible using a set of 9 letters, the words can be between 4 and 9 letters long (the words are anagrams of the original 9 letters but do not have to be 9 letters long). The set of 9 letters are read in as a string from the user. Basically the function needs to check the words in a word list (txt file which is converted to list of strings) if they are anagrams of the user inputs, and if so print word to the screen.

I have tried the python all() function but does not work since it does not take into account the frequency of characters in the user input (example: if user input contains only two A's, word should not be printed if it contains more than two A's).

1

There are 1 best solutions below

0
Rubén Pérez On

You could use something like this:

# Prints all the anagrams
def check(letters, word):
    if(sorted(letters) <= sorted(word)):
        print(word)
# NOTE: 'letters' is the user input. As this function is going to be called a lot of times, user input should be sorted outside this function.
# Cabs: True
check('aabbcccss', 'cabs')
# Array: False (two A's needed and two R's needed)
check('aryqwetyu', 'array')

If you want to know the letters of every word that are not included in the user input, you could use Counter instead: https://docs.python.org/3/library/collections.html#collections.Counter.subtract

from collections import Counter

# Prints the letters included in the word, but not included in the user's input
def check(letters, word):
    print(f'{letters} - {word}')
    c = Counter(letters)
    w = Counter(word)
    c.subtract(w)
    for k,v in dict(c).items():
        if v < 0:
            print(f'{-v} {k}\'s missing.')
    print('--------')
# cabs - aabbcccss
# --------
check('aabbcccss', 'cabs')
# array - aryqwetyu
# 1 a's missing.
# 1 r's missing.
# --------
check('aryqwetyu', 'array')