我试图找到/编写一个函数来比较Python程序中解决单词谜题游戏中的两个单词。游戏的目标是使用一组9个字母创建尽可能多的单词,单词可以在4到9个字母之间(单词是原始9个字母的字谜,但不必是9个字母长)。这组9个字母作为字符串从用户中读取。基本上,函数需要检查单词列表(txt文件,转换为字符串列表)中的单词是否是用户输入的字谜,如果是,则将单词打印到屏幕上。
我尝试过python ()函数,但是它没有工作,因为它没有考虑到用户输入中字符的频率(例如:如果用户输入只包含两个A,则如果包含两个以上的A,则不应该打印word )。
发布于 2022-09-09 12:00:14
你可以用这样的东西:
# 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')如果您想知道用户输入中没有包含的每个单词的字母,可以使用计数器: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')https://stackoverflow.com/questions/73661265
复制相似问题