Những gì tôi đang làm gì ở đây là để có được tất cả các vị trí phân chia thể của chuỗi và loại bỏ chuỗi cuối cùng. Ví dụ:
ví dụ, trong một số chuỗi có 5 số "12345", có 4 vị trí có thể tách chuỗi, gọi là possibility = (0,0,0,0),(1,0,1,0)
... với (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)
để bạn có thể nhận được tất cả các khả năng trong khi điều kiện của bạn được xác minh từ chúng tôi loại bỏ trường hợp (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
']
Có thể nó có thể giúp bạn [List Comprehension] (https: // docs. python.org/2/tutorial/datastructures.html#list-comprehensions) –
Bằng tập con, bạn có nghĩa là một chuỗi con? – geckon
Tôi nghĩ bạn quan tâm đến [bộ nguồn] (https://stackoverflow.com/questions/1482308/whats-a-good-way-to-combinate-through-a-set) – CoryKramer