python - 编写一个程序,在Python中显示 "abcdef"的所有字谜

标签 python anagram

我的 friend 写了一段代码来显示 python 中“abcdef”的所有字谜。但在这段代码中,我无法理解递归过程是如何工作的 anagrams = get_list_of_anagrams(''.join(tmp_list)) 函数如何调用自身?

def get_list_of_anagrams(s):
    if len(s)==0:
        return ['']
    all_chars = list(s)
    unique_chars = list(set(s))
    anagrams_list = []
    for char in unique_chars:
        tmp_list = list(all_chars)
        tmp_list.remove(char)
        anagrams = get_list_of_anagrams(''.join(tmp_list))
        for i in range(len(anagrams)):
            anagrams[i] = char+anagrams[i]
        anagrams_list += anagrams
    return anagrams_list

当我尝试打印所有内容时,直到anagrams = get_list_of_anagrams(''.join(tmp_list)

def get_list_of_anagrams(s):
    if len(s)==0:
        return ['']
    all_chars = list(s)
    unique_chars = list(set(s))
    anagrams_list = []
    for char in unique_chars:
        tmp_list = list(all_chars)
        tmp_list.remove(char)
        anagrams = get_list_of_anagrams(''.join(tmp_list))



print get_list_of_anagrams('abc')

我得到以下输出。

enter image description here

对于以下代码:

def get_list_of_anagrams(s):
    if len(s)==0:
        return ['']
    all_chars = list(s)
    unique_chars = list(set(s))
    anagrams_list = []
    for char in unique_chars:
        tmp_list = list(all_chars)
        tmp_list.remove(char)
        anagrams = get_list_of_anagrams(''.join(tmp_list))
        print anagrams
        for i in range(len(anagrams)):
            anagrams[i] = char+anagrams[i]
        anagrams_list += anagrams
    return anagrams_list  

print get_list_of_anagrams('abc')

我得到以下输出:

enter image description here

有人可以解释一下为什么上面的输出是这种模式吗?

最佳答案

生命短暂,使用库:

import itertools
d = 'abc'
e = len(d)
j = list()

for p in itertools.permutations(d, e):
    print p

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

关于python - 编写一个程序,在Python中显示 "abcdef"的所有字谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28733761/

相关文章:

python - 合并属于时间序列一部分的多个数据文件(具有多个列)

python - 将类实例合并到Python中的另一个实例中?

python - 将程序从 FreeBASIC 转换为 Python : globalizing variables

javascript - 快速字谜检查算法 (HackerRank)

c++ - 优化非常常用的字谜函数

python - 有向图中的循环

python - lxml etree.iterparse 错误 "TypeError: reading file objects must return plain strings"

c# - 字谜算法

查找单词字谜数量的算法?

php - 对字谜解算器实现空白平铺搜索的最佳实践