Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all possible combinations of a string when splitted into n strings

I made a search for stackoverflow about this but couldn't find a way to do it. It probably involves itertools.

I want to find all the possible results of splitting a string, say the string thisisateststring into n (equal or unequal length, doesn't matter, both should be included) strings.

For example let n be 3:

[["thisisat", "eststrin", "g"], ["th", "isisates", "tstring"], ............]
like image 939
user3507230 Avatar asked Jan 10 '23 20:01

user3507230


1 Answers

You can use itertools.combinations here. You simply need to pick two splitting points to generate each resulting string:

from itertools import combinations
s = "thisisateststring"
pools = range(1, len(s))
res = [[s[:p], s[p:q], s[q:]] for p, q in combinations(pools, 2)]
print res[0]
print res[-1]

Output:

['t', 'h', 'isisateststring']
['thisisateststri', 'n', 'g']
like image 55
YS-L Avatar answered Jan 21 '23 14:01

YS-L