查找给定字符串中包含的字谜

Posted

技术标签:

【中文标题】查找给定字符串中包含的字谜【英文标题】:Finding anagrams contained in a given string 【发布时间】:2015-12-27 22:38:51 【问题描述】:

我正在尝试编写一个接受字符串并将字谜分组的程序 将字符串放在列表列表中,按字典顺序排序。

例如下面的字符串:

eat tea tan ate nat bat

应该产生以下输出(行的顺序很重要):

ate eat tea
bat
nat tan

我写的程序:

from collections import defaultdict

def get_anagrams(source):
d = defaultdict(list)
for word in source:
    key = "".join(sorted(word))
    d[key].append(word)
return d

def print_anagrams(my_string):
word_source = my_string.split(" ")
d = get_anagrams(word_source)
for key, anagrams in d.items():
    print(" ".join(sorted(anagrams)))

print_anagrams("eat tea tan ate nat bat")

这个程序产生正确的字谜,但每次我运行程序时,行的顺序与预期的输出变化相比。

所以有时我会得到

nat tan
ate eat tea
bat

其他时候我确实得到了正确的输出

ate eat tea
bat
nat tan

谁能指出我做错了什么?

【问题讨论】:

请不要破坏自己的问题,一旦它吸引了答案。 【参考方案1】:

您在那里有一个dictionary,如果您使用for key, anagrams in d.items(): 对其进行迭代,您将无法保证订购:

字典对象的keys() 方法返回一个包含所有 字典中使用的键,以任意顺序(如果你想要的话 排序后,只需将sorted() 函数应用于它)。检查是否有 单键在字典中,使用 in 关键字。

因此,您可以像这样编辑您的代码,以遍历已排序的字典按键排序):

for key, anagrams in sorted(d.items()):
    print(" ".join(sorted(anagrams)))

这保证了输出总是

bat
ate eat tea
nat tan

【讨论】:

感谢您的回复,但正确的输出有第一行:吃了吃茶等等。您的建议仍然没有产生正确的输出。 如果字谜必须按照它们在原始文本中出现的顺序打印,请使用OrderedDict @Landon:然后相应地修复你的程序,现在你知道发生了什么:) @alexanderlukanin13:我认为这是家庭作业,因此OrderedDict 可能被老师认为是作弊(再说一次,当我们在谈论字谜时,cheaterteacher 的字谜:P) @Landon:我不会打扰。使用常规数据结构修复您的程序。我建议你稍微研究一下,既然你知道字典的棘手部分,当你偶然遇到另一个问题时,可能会打开另一个问题,这样我们就可以专注于那个:) 请注意,如果你的问题变成“为我做作业”它可能会关闭。【参考方案2】:

字典键的顺序是随机设计的。

如果您想按照它们在原始文本中出现的顺序打印字谜,请使用OrderedDict,它按照您插入它们的顺序存储键:

from collections import OrderedDict

def get_anagrams(source):
    d = OrderedDict()
    for word in source:
        key = "".join(sorted(word))
        if key not in d:
            d[key] = []
        d[key].append(word)
    return d

def print_anagrams(my_string):
    word_source = my_string.split(" ")
    d = get_anagrams(word_source)
    for key, anagrams in d.items():
        print(" ".join(sorted(anagrams)))

print_anagrams("eat tea tan ate nat bat")

输出:

ate eat tea
nat tan
bat

【讨论】:

以上是关于查找给定字符串中包含的字谜的主要内容,如果未能解决你的问题,请参考以下文章

查找给定单词的字谜

在给定的字符串列表中查找字符串的所有字谜

使用 .bat 文件在目录中包含的多个文件中查找和替换字符串

正则表达式 - 查找字谜和子字谜

查找 N 个字符串是不是是彼此的字谜

查找字符串中的所有字谜如何优化