函数比较单词以解决Python中的单词游戏



我试图在Python程序中找到/编写一个函数来比较两个单词,该程序解决了一个单词拼图游戏。游戏的目标是使用一组9个字母创建尽可能多的单词,这些单词的长度可以在4到9个字母之间(这些单词是原始9个字母的变位符,但不必是9个字母长(。这组9个字母作为字符串从用户那里读取。基本上,该函数需要检查单词列表(txt文件,转换为字符串列表(中的单词是否为用户输入的变位符,如果是,则将单词打印到屏幕上。

我尝试过python all((函数,但它不起作用,因为它没有考虑用户输入中字符的频率(例如:如果用户输入只包含两个A,那么如果单词包含两个以上的A,就不应该打印它(。

您可以使用这样的东西:

# 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')

如果你想知道用户输入中没有包含的每个单词的字母,你可以使用Counter: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')

最新更新