使用Counter()在字典中查找变位词的关键字



我正试图在想象中的字典中寻找具有相似字母(变位符(的密钥,但我有一个不完整的代码:

from collections import Counter
diction = {'crazy':'dd', 'abd':'ddd','cat':'bad'}
word = input('what is the word?')
new=[]
for i in dic:
if(Counter(word) == Counter(....):
new.append(...)
else:
continue

print(f'{word} and {new} are anagrams')

我不知道如何检查这些键,以及它们是否与给定的输入相匹配。感谢您的帮助

我实际上认为Counter是一个很好的解决方案,可能比排序更好,因为它是O(n(。例如,Counter("arc") == Counter("car")返回True。所以你走在了正确的轨道上。

您的代码中存在拼写错误(dic应为diction(。你的for循环已经在密钥中迭代了,所以你很接近:

from collections import Counter
diction = {'crazy':'dd', 'abd':'ddd','cat':'bad'}
word = input('what is the word?')
new=[]
for i in diction:
if(Counter(word) == Counter(i)):
new.append(i)
else:
continue

print(f'{word} and {new} are anagrams')

如果我输入"0";tac";,它将打印:

tac和['cat']是变位词

最新更新