顺序重要的组合-Python



我有这个问题,我需要显示文本条目中所有可能的"子集",例如:

-条目:ab

(a,b(和(ab(

条目:abc

(a,b,c(和(ab,c(以及(a,bc(和(abc(

条目:abcd

(a,b,c,d(和(a,bcd(和

我的所有"子集"都需要与我的所有元素条目保持相同的顺序,我进行数学运算,子集的数量是2^(n-1(,n是字母的数量,如果个人多次输入同一个字母,也没有限制。

我不知道该怎么开始,我想我需要一些递归函数,有人告诉我回溯,但我不知道如何实现

感谢阅读我的

问题归结为将多个逗号分配到n-1个可能的位置(其中n是列表中的条目数(。逗号的数量可以是1到n-1之间的任何值,因此我们需要对其进行迭代,并获得相应数字的所有不同组合。这可以通过来自itertools包的例程combinations来完成。

import itertools
mylist = [1, 2, 3, 4]# this is the list from which to draw the subsets
print ([mylist])# the first subsequence of the list is the list itself
# iterating through the possible numbers of commas to be distributed
for n in range(1, len(mylist)):
comma_positions_comb = list( itertools.combinations(range(1, len(mylist)), n) )
# iterating through the combinations of comma positions
for comma_positions in comma_positions_comb:
subset = []
start_id = 0
# iterating through the specific comma positions in the given combination
for single_comma_position in comma_positions:
subset.append(mylist[start_id:single_comma_position])
start_id = single_comma_position
# the last bit of the list must be appended by hand
subset.append(mylist[start_id:])
print (subset)

这给了我以下输出:

[[1, 2, 3, 4]]
[[1], [2, 3, 4]]
[[1, 2], [3, 4]]
[[1, 2, 3], [4]]
[[1], [2], [3, 4]]
[[1], [2, 3], [4]]
[[1, 2], [3], [4]]
[[1], [2], [3], [4]]

从你举的例子来看,这应该是你想要的。请注意,并没有包括更多嵌套的子集,如[1, [2, [3, [4]]]],对应于(a,(b,(c,d((,但似乎您无论如何都不想把它们弄出来。

最新更新