[我想我即将根据我所设置的词典中的用户输入来弄清楚如何打印所有可能的单词。它基于这样的假设:用户输入为“ ART”,因此我在词典中输入的可能单词是ART,RAT,TART和TAR,但仅打印出三个字母组合。谁能告诉我我要去哪里错了?谢谢!
Dictionary = ["tar","art","tart","rat"] #creates dictionary of set words
StoredLetters = input('input your word here: ') #allows the user to input any word
list(StoredLetters)
def characters(word):
Dictionary = {}
for i in word:
Dictionary[i] = Dictionary.get(i, 0) + 1
return Dictionary
def all_words(StoredLetters, wordSet):
for word in StoredLetters:
flag = 1
words = characters(word)
for key in words:
if key not in wordSet:
flag = 0
else:
if wordSet.count(key) != words[key]:
flag = 0
if flag == 1:
print(word)
if __name__ == "__main__":
print(all_words(Dictionary, StoredLetters))
似乎有一些事情可能对此有所帮助。
当您在主def allwords(Dictionary, StoredLetters):
中调用它时,将交换所有单词allwords(StoredLetters, Dictionary)
上的参数。如果不指定名称(在python中查找命名参数),则将交换输入。
在characters
函数中,您似乎正在重置字典变量。创建新变量时,请尝试使用唯一名称。这会导致在调用characters(word)
时清空您在顶部设置的单词词典
首先,通过使变量StoredLetters
的名称也成为all_words
函数的自变量之一的名称,使您感到困惑。
[第二,实际上是将StoredLetters
传入,即art
,作为函数的第二个参数,因此它是函数中的wordSet
,而不是StoredLetters
!
您实际上应该通过使用不同的变量名使事情变得更加清晰,并且清楚地知道您对哪个参数使用了什么。 words
并不是真正的单词,它是一个以字母为键的字典,它们多少次作为值出现!使代码清晰易懂可大大简化调试过程。您有word
,StoredLetters
,wordSet
,另一个StoredLetters
自变量words = characters(word)
,该参数没有执行预期的操作。这都可以使用良好的清理方法。
关于功能,对于art
,每个字母仅出现一次,因此对于具有tart
两次的t
,if wordSet.count(key) != words[key]
的值为True,并且标记将设置为0,并且单词将不会打印。
希望有帮助,祝您编程愉快!