给定一个字符串,我想生成所有可能的组合.换句话说,将逗号放在字符串中的所有可能方法.
例如:
input: ["abcd"] output: ["abcd"] ["abc","d"] ["ab","cd"] ["ab","c","d"] ["a","bc","d"] ["a","b","cd"] ["a","bcd"] ["a","b","c","d"]
我有点坚持如何生成所有可能的列表.组合将只给出包含字符串集子集长度的列表,排列将提供所有可能的订购方式.
由于遍历切片,我可以在列表中只使用一个逗号来创建所有情况,但是我不能用两个逗号来表示例如"ab","c","d"和"a","b" ,"光盘"
我的尝试w/slice:
test="abcd" for x in range(len(test)): print test[:x],test[x:]
DSM.. 15
怎么样的:
from itertools import combinations def all_splits(s): for numsplits in range(len(s)): for c in combinations(range(1,len(s)), numsplits): split = [s[i:j] for i,j in zip((0,)+c, c+(None,))] yield split
之后:
>>> for x in all_splits("abcd"): ... print(x) ... ['abcd'] ['a', 'bcd'] ['ab', 'cd'] ['abc', 'd'] ['a', 'b', 'cd'] ['a', 'bc', 'd'] ['ab', 'c', 'd'] ['a', 'b', 'c', 'd']
Tim Peters.. 15
你当然可以使用itertools
它,但我认为直接编写递归生成器更容易:
def gen_commas(s): yield s for prefix_len in range(1, len(s)): prefix = s[:prefix_len] for tail in gen_commas(s[prefix_len:]): yield prefix + "," + tail
然后
print list(gen_commas("abcd"))
版画
['abcd', 'a,bcd', 'a,b,cd', 'a,b,c,d', 'a,bc,d', 'ab,cd', 'ab,c,d', 'abc,d']
我不确定为什么我觉得这更容易.也许只是因为直接做到这一点很容易;-)
怎么样的:
from itertools import combinations def all_splits(s): for numsplits in range(len(s)): for c in combinations(range(1,len(s)), numsplits): split = [s[i:j] for i,j in zip((0,)+c, c+(None,))] yield split
之后:
>>> for x in all_splits("abcd"): ... print(x) ... ['abcd'] ['a', 'bcd'] ['ab', 'cd'] ['abc', 'd'] ['a', 'b', 'cd'] ['a', 'bc', 'd'] ['ab', 'c', 'd'] ['a', 'b', 'c', 'd']
你当然可以使用itertools
它,但我认为直接编写递归生成器更容易:
def gen_commas(s): yield s for prefix_len in range(1, len(s)): prefix = s[:prefix_len] for tail in gen_commas(s[prefix_len:]): yield prefix + "," + tail
然后
print list(gen_commas("abcd"))
版画
['abcd', 'a,bcd', 'a,b,cd', 'a,b,c,d', 'a,bc,d', 'ab,cd', 'ab,c,d', 'abc,d']
我不确定为什么我觉得这更容易.也许只是因为直接做到这一点很容易;-)