python求字符串的所有子集,python字符串子集的所有组合

我要做的是得到所有可能的弦的分裂位置,然后消除最后一个。在

例如,在一些有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

']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值