我要做的是得到所有可能的弦的分裂位置,然后消除最后一个。在
例如,在一些有5个数字“12345”的字符串中,有4个可能的位置可以拆分字符串,称之为possibility = (0,0,0,0),(1,0,1,0)。。。使用(0,0,1,0) mean (don't separate 1 and 2345,don't separate 12 and 345,separate 123 and 45,don't separate 1234 and 5),这样您就可以获得所有的可能性,同时验证您的条件,因为我们消除了(1,1,1,1)的情况。在import itertools
from math import factorial
from itertools import product
def get_comb(string):
L = len(string_)
combinisation = []
for possibility in product([0,1], repeat=len(string_)-1):
s = []
indexes = [i for i in range(len(string_)-1) if list(possibility)[i]!=0]
if sum(indexes) != 0:
if sum(indexes) != len(string_)-1:
for index in indexes:
s.append(string_[:index+1])
s.append(string_[indexes[-1:][0]+1:])
combinisation.append(s)
else:
combinisation.append(string_)
return combinisation
string_ = '4824'
print "%s combinations:"%string_
print get_comb(string_)
string_ = '478952'
print "%s combinations:"%string_
print get_comb(string_)
string_ = '1234'
print "%s combinations:"%string_
print get_comb(string_)
>>
4824 combinations:
[['482', '4'], ['48', '24'], '4824', ['4', '482', '4'], ['4', '48', '24'], '4824
']
478952 combinations:
[['47895', '2'], ['4789', '52'], ['4789', '47895', '2'], ['478', '952'], ['478',
'47895', '2'], '478952', ['478', '4789', '47895', '2'], ['47', '8952'], '478952
', ['47', '4789', '52'], ['47', '4789', '47895', '2'], ['47', '478', '952'], ['4
7', '478', '47895', '2'], ['47', '478', '4789', '52'], ['47', '478', '4789', '47
895', '2'], ['4', '47895', '2'], ['4', '4789', '52'], ['4', '4789', '47895', '2'
], ['4', '478', '952'], ['4', '478', '47895', '2'], '478952', ['4', '478', '4789
', '47895', '2'], ['4', '47', '8952'], '478952', ['4', '47', '4789', '52'], ['4'
, '47', '4789', '47895', '2'], ['4', '47', '478', '952'], ['4', '47', '478', '47
895', '2'], ['4', '47', '478', '4789', '52'], ['4', '47', '478', '4789', '47895'
, '2']]
1234 combinations:
[['123', '4'], ['12', '34'], '1234', ['1', '123', '4'], ['1', '12', '34'], '1234
']