如何使用计数器在Python中创建一个打印字符串顺序的变位词?

huangapple go评论62阅读模式
英文:

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']]

huangapple
  • 本文由 发表于 2023年2月18日 07:12:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定