How to set a number of loop 'for' as a parameter of a function in python to find all the possibility to cut a period in n parts?

Question:

Here is a ugly code to find all the possibilities to cut a period in 5 parts. Is there a possibility to create a function which makes it look better, with the number of cut as a parameter ?

I am only abble to write each for loop :

part_list = pd.DataFrame(columns=['period_array'])
for i in range(1, period_size):
    for j in range(1, period_size - i):
        for h in range(1, period_size - (i + j)):
            for g in range(1, period_size - (i + j + h)):
                part_list = part_list.append({'period_array':
                                                  np.array([[0, i],
                                                            [i, i + j],
                                                            [i + j, i + j + h],
                                                            [i + j + h, i + j + h + g],
                                                            [i + j + h + g, period_size]])},
                                             ignore_index=True)
Asked By: Riaf Sinay

||

Answers:

Using function combinations from module itertools to generate all combinations of cutting points:

from itertools import combinations, chain, pairwise

def all_cuts(seq, n):
    for comb in combinations(range(1,len(seq)), n-1):
        yield tuple(seq[i:j] for i,j in pairwise(chain((0,), comb, (len(seq),))))

print( list(all_cuts('Hello, World!', 3)) )
# [('H', 'e', 'llo, World!'), ('H', 'el', 'lo, World!'),
#  ('H', 'ell', 'o, World!'), ('H', 'ello', ', World!'),
#  ('H', 'ello,', ' World!'), ...
#                        ..., ('Hello, Wor', 'l', 'd!'),
#  ('Hello, Wor', 'ld', '!'), ('Hello, Worl', 'd', '!')]
Answered By: Stef