I would split the partitioning from the bracketing part and create two generators, one for each. Then a third generator can take care of producing the desired result:
def bracket(p):
n = len(p)
yield p
for i in range(0, n-1):
left = p[:i]
for j in range(i + 2, n + 1 - (i == 0)):
suffix = p[j:]
for mid in bracket(p[i:j]):
for right in bracket(suffix):
yield left + (mid,) + right
if len(right) >= 2:
yield left + (mid,) + (right,)
def partitions(n):
yield (n,)
for i in range(1, n):
for p in partitions(n - i):
yield (i,) + p
def nested_partitions(n):
for p in partitions(n):
yield from bracket(p)
For n
equal to 5 this generates 112 tuples:
(5,)
(1, 4)
(1, 1, 3)
((1, 1), 3)
(1, (1, 3))
(1, 1, 1, 2)
((1, 1), 1, 2)
((1, 1), (1, 2))
((1, 1, 1), 2)
(((1, 1), 1), 2)
((1, (1, 1)), 2)
(1, (1, 1), 2)
(1, (1, 1, 2))
(1, ((1, 1), 2))
(1, (1, (1, 2)))
(1, 1, (1, 2))
(1, 1, 1, 1, 1)
((1, 1), 1, 1, 1)
((1, 1), (1, 1, 1))
((1, 1), (1, 1), 1)
((1, 1), ((1, 1), 1))
((1, 1), 1, (1, 1))
((1, 1), (1, (1, 1)))
((1, 1, 1), 1, 1)
((1, 1, 1), (1, 1))
(((1, 1), 1), 1, 1)
(((1, 1), 1), (1, 1))
((1, (1, 1)), 1, 1)
((1, (1, 1)), (1, 1))
((1, 1, 1, 1), 1)
(((1, 1), 1, 1), 1)
(((1, 1), (1, 1)), 1)
(((1, 1, 1), 1), 1)
((((1, 1), 1), 1), 1)
(((1, (1, 1)), 1), 1)
((1, (1, 1), 1), 1)
((1, (1, 1, 1)), 1)
((1, ((1, 1), 1)), 1)
((1, (1, (1, 1))), 1)
((1, 1, (1, 1)), 1)
(1, (1, 1), 1, 1)
(1, (1, 1), (1, 1))
(1, (1, 1, 1), 1)
(1, ((1, 1), 1), 1)
(1, (1, (1, 1)), 1)
(1, (1, 1, 1, 1))
(1, ((1, 1), 1, 1))
(1, ((1, 1), (1, 1)))
(1, ((1, 1, 1), 1))
(1, (((1, 1), 1), 1))
(1, ((1, (1, 1)), 1))
(1, (1, (1, 1), 1))
(1, (1, (1, 1, 1)))
(1, (1, ((1, 1), 1)))
(1, (1, (1, (1, 1))))
(1, (1, 1, (1, 1)))
(1, 1, (1, 1), 1)
(1, 1, (1, 1, 1))
(1, 1, ((1, 1), 1))
(1, 1, (1, (1, 1)))
(1, 1, 1, (1, 1))
(1, 1, 2, 1)
((1, 1), 2, 1)
((1, 1), (2, 1))
((1, 1, 2), 1)
(((1, 1), 2), 1)
((1, (1, 2)), 1)
(1, (1, 2), 1)
(1, (1, 2, 1))
(1, ((1, 2), 1))
(1, (1, (2, 1)))
(1, 1, (2, 1))
(1, 2, 2)
((1, 2), 2)
(1, (2, 2))
(1, 2, 1, 1)
((1, 2), 1, 1)
((1, 2), (1, 1))
((1, 2, 1), 1)
(((1, 2), 1), 1)
((1, (2, 1)), 1)
(1, (2, 1), 1)
(1, (2, 1, 1))
(1, ((2, 1), 1))
(1, (2, (1, 1)))
(1, 2, (1, 1))
(1, 3, 1)
((1, 3), 1)
(1, (3, 1))
(2, 3)
(2, 1, 2)
((2, 1), 2)
(2, (1, 2))
(2, 1, 1, 1)
((2, 1), 1, 1)
((2, 1), (1, 1))
((2, 1, 1), 1)
(((2, 1), 1), 1)
((2, (1, 1)), 1)
(2, (1, 1), 1)
(2, (1, 1, 1))
(2, ((1, 1), 1))
(2, (1, (1, 1)))
(2, 1, (1, 1))
(2, 2, 1)
((2, 2), 1)
(2, (2, 1))
(3, 2)
(3, 1, 1)
((3, 1), 1)
(3, (1, 1))
(4, 1)
This grows exponentially. For n=10
, there are over half a million tuples.