python string operation. sticked words separation

Viewed 48

I have a pretty challenging problem here I need your help.

the problem is this:

I have a string for example "abcde"

Now, I want to separate this string into any possible ordered combinations as a list of strings. for example,

my_function('abcde')

output = 
[
 ['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'de'],
 ['a', 'b', 'cde'],
 ['a', 'bced'],
 ['a', 'b', 'cd', 'e'],
 ['a', 'bc', 'd', 'e'],
 ['a', 'bc', 'de'],
 ['a', 'bcd', 'e'],
 ['a', 'bcde'],
 ['ab', 'c', 'd', 'e'],
 ['ab', 'c', 'de'],
 ['ab', 'cd', 'e'],
 ['ab', 'cde'],
 ['abc','d','e'],
 ['abc', 'de'],
 ['abcd', 'e'],
 ['abcde']
]

It is not quite the permutation since the order matters.

3 Answers

You could do this:

import itertools

def get_slices(values):
    slices_len = len(values) - 1

    for is_slice in itertools.product([True, False], repeat=slices_len):
        start_index = 0
        slices = []

        for slice_index, is_index_slice in enumerate(is_slice, 1):
            if is_index_slice:
                index_slice = values[start_index:slice_index]
                start_index = slice_index

                slices.append(index_slice)

        slices.append(values[start_index:])

        yield slices

Most important part of this code is the itertools.product call at the beginning, this generates all possible types of slices. A slice definition here corresponds to a bunch of bools representing whether two adjacent elements at all indices of pairs in values (there are slices_len of these) are joined or not.

list(get_slices("abcde)) will return the list you requested. If you don't need all results immediately, and instead want to iterate through them, you don't need the surrounding list call.

If you want the reverse order, you can switch the [True, False] with [False, True].

Same result without itertools:

s = 'python'
splits = len(s) - 1
output = []
for i in range(2 ** splits):
    combination = []
    word = ''
    for position in range(splits + 1):
        word += s[position]
        if not (i & (1 << position)):
            combination.append(word)
            word = ''
    output.append(combination)
output.sort()

for combination in output:
    print(combination)

Just for beginners.

i got 16 items and you have 17 :-)

    def fn(base_str):
        result = [[base_str]]
        for i in range(1, len(base_str)):
            child = fn(base_str[i:])
            for x in child:
                x.insert(0, base_str[0:i])
            result = child + result
        return result


    print(fn("abcde"))
Related