Excuse me, ignore my previous post, this is the correct implementation. It
works for every iterable:
import itertools as itools
def segment(it, n=1):
if n < 1:
raise ValueError(f"Number of segment must be > 0")
try:
len_it = len(it)
it[0:0]
it_true = it
except TypeError:
it_true = tuple(it)
len_it = len(it_true)
if len_it < n:
raise ValueError(f"Iterable length {len_it} must be greater than
number of segments {n}")
size, rest = divmod(len_it, n)
sizes = [size] * n
orig_sizes = sizes.copy()
all_sizes = []
for i in range(1, rest+1):
for j in range(1, rest-i+2):
sizes[-j] += i
all_sizes.append(frozenset(itools.permutations(sizes)))
sizes = orig_sizes.copy()
if not all_sizes:
all_sizes.append((sizes, ))
res = []
for perm_sizes in all_sizes:
for sizes in perm_sizes:
elem = []
i = 0
for size in sizes:
elem.append(it_true[i:i+size])
i += size
res.append(elem)
return res
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/E452LQGA3XKU5ADPTG54XP36ENXDZN2B/
Code of Conduct: http://python.org/psf/codeofconduct/