英文:
How to create an anagram that prints an order of string in python using counter?
问题
from collections import Counter, defaultdict
def checking_anagram(keywords):
agrms = defaultdict(list)
for i in keywords:
hist = tuple(Counter(i).items())
agrms[hist].append(i)
return list(agrms.values())
keywords = ("eat","tea","tan","ate","nat","bat","bat")
print(checking_anagram(keywords))
英文:
I am struggling to create an order of string using counter in python and my program is not printing an order of the given string below.
from collections import Counter, defaultdict
def checking_anagram(keywords):
agrms = defaultdict(list)
for i in keywords:
hist = tuple(Counter(i).items())
agrms[hist].append(i)
return list(agrms.values())
keywords = ("eat","tea","tan","ate","nat","bat","bat")
print(checking_anagram(keywords))
答案1
得分: -1
你唯一真正的问题在于你的 hist
行。我不知道你尝试做什么,但那是错误的。你需要做的是对每个单词的字母进行排序,然后将其用作你的键:
from collections import defaultdict
def checking_anagram(keywords):
agrms = defaultdict(list)
for word in keywords:
s = ''.join(sorted(word))
agrms展开收缩.append(word)
return list(agrms.values())
keywords = ("eat","tea","tan","ate","nat","bat")
print(checking_anagram(keywords))
输出:
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat', 'bat']]
英文:
The only real problem you have is your hist
line. I don't know what you were trying to do, but that is wrong. What you need to do is sort the letters of each word, and use that as your key:
from collections import defaultdict
def checking_anagram(keywords):
agrms = defaultdict(list)
for word in keywords:
s = ''.join(sorted(word))
agrms展开收缩.append(word)
return list(agrms.values())
keywords = ("eat","tea","tan","ate","nat","bat")
print(checking_anagram(keywords))
Output:
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat', 'bat']]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论