使用 collections.Counter() 在 Python 中检查字谜

pythonserver side programmingprogramming更新于 2025/10/18 16:12:17

当两个字符串具有相同的字符但排列顺序不同时,它们被称为字谜。例如,spot 和 post 就是字谜,因为它们具有相同的字母,但形成了不同的单词。在本文中,我们将了解如何检查两个字符串是否是彼此的字谜。

为此,我们使用名为 collections 的 Python 模块。它用于存储数据集合,如列表、字典、集合、元组等。这些是内置集合的示例。函数 counter() 仅计算元素在集合中出现的次数,并将结果作为显示元素及其计数的字典返回。因此,如果两个字符串中每个字符的计数都匹配,则我们将它们视为字谜。

示例

from collections import Counter
StringA = 'top spot'
StringB = 'pot post'
# 将元素打印为字典
print Counter(StringA)
print Counter(StringB)
# 比较字典
if Counter(StringA)== Counter(StringB):
print 'StringA and StringB are Anagrams'

输出

运行上述代码得到以下结果 −

Counter({'p': 2, 't': 2, 'o': 2, 's': 1, ' ': 1})
Counter({'p': 2, 't': 2, 'o': 2, 's': 1, ' ': 1})
StringA and StringB are Anagrams

相关文章


有用资源