Is there a builtin solution (I'd imagine in itertools
but couldn't find it myself) to partition an int n
(e.g. 4) into its ordered groups of summands (1+1+1+1, 1+1+2, 1+2+1, 2+1+1, ...).
Here's the fastest hand-coded implementation I could find: accel_asc
def accel_asc(n):
a = [0 for i in range(n + 1)]
k = 1
y = n - 1
while k != 0:
x = a[k - 1] + 1
k -= 1
while 2 * x <= y:
a[k] = x
y -= x
k += 1
l = k + 1
while x <= y:
a[k] = x
a[l] = y
yield a[:k + 2]
x += 1
y -= 1
a[k] = x + y
y = x + y - 1
yield a[:k + 1]
Which doesn't generate all permutations, but I can just call set(itertools.permutations
on each.
Is there anything faster than that?