0

How might I find all the partitions of n that have length less-than-or-equal-to L?

jonnybolton16
  • 193
  • 2
  • 11

1 Answers1

0

Based on the code given here, we can include an additional argument L (which defaults to n).

We might naively include if len((i,) + p) <= L: before yield (i,) + p. However, since len((i,) + p) = 1 + len(p), any partitions of n-i that are longer than L-1 are discarded. Thus time is wasted by finding them. Instead, we should include L=L-1 as an argument when finding partitions of n-1. We then need to deal with the L=0 case properly, by not running the main body:

def partitions(n, L=None, I=1):
    if L is None:
        L = n
    
    if L:
        yield (n,)
        for i in range(I, n//2 + 1):
            for p in partitions(n-i, L-1, i):
                yield (i,) + p

Now if L=1, the for i loop will be executed, but none of the for p loops will since the partitions calls won't yield anything; we need not execute the for i loop at all in this case, which can save a lot of time:

def partitions(n, L=None, I=1):
    if L is None:
        L = n
    
    if L == 1:
        yield (n,)
    elif L > 1:
        yield (n,)
        for i in range(I, n//2 + 1):
            for p in partitions(n-i, L-1, i):
                yield (i,) + p
jonnybolton16
  • 193
  • 2
  • 11