Python每个可能的字符串组合

时间:2015-03-05 05:31:24

标签: python string recursion combinations permutation

嗨,所以我正在使用python,我试图编写一个给定字符串的方法,它会找到该字符串的每个组合并将其附加到列表中。我会给出字符串并显示我想要的结果。

字符串:x = 'god'

结果:

lst = ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']

字母只能按给定字符串显示的次数使用,因此如果我们的字符串为'god',则'gg''goo'等不能追加。如果这可以使用递归来完成,那就太好了!

5 个答案:

答案 0 :(得分:4)

使用itertools.permutations和列表推导

from itertools import permutations
[''.join(j) for i in range(1,len(x) + 1) for j in  permutations(x, i)]

<强>输出

['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']

答案 1 :(得分:1)

您想使用itertools。从你写的内容来看,听起来你想使用itertools.permutation

>>> import itertools
>>> letters = 'god'
>>> combinations = []
>>> for i in range(len(letters)):
...     combinations.extend(
...         [''.join(x) for x in itertools.permutations(letters, i + 1)])
>>> print(combinations)
['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']

答案 2 :(得分:1)

使用permutations

from itertools import permutations

x = 'god'


perms = []

for i in range(1, len(x)+1):
    for c in permutations(x, i):
        perms.append("".join(c))

print(perms) 
# ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']

答案 3 :(得分:0)

你在这里尝试做的是获取你传入的任何字符串的powerset。你想要做的是将该字符串转换为字符列表,然后使用定义powersets使用简单的列表扩展来创建您要查找的内容。

def list_powerset(lst): # the power set of the empty set has one element, the empty set result = [[]] for x in lst: # for every additional element in our set # the power set consists of the subsets that don't # contain this element (just take the previous power set) # plus the subsets that do contain the element (use list # comprehension to add [x] onto everything in the # previous power set) result.extend([subset + [x] for subset in result]) return result

上述代码位于http://rosettacode.org/wiki/Power_set#Python

答案 4 :(得分:0)

import itertools

def _itersubs(x):
    for i in range(1, len(x)+1):
        yield from itertools.permutations(x, i)
        # before 3.4, replace with:
        # for y in itertools.permutations(x, i): yield y

def thefuncyouwant(x):
    return list(_itersubs(x))

我不确定你实际上想要一个2 ** len(x)项列表 - 对于任何x来说,它会占用很多的内存不是很短 - 但是,这就是你要求的,所以在这里。迭代器一次产生一个项目显然更自然,可能更可取,但只需将它包裹在list调用就会消耗掉你想要的内存! - )