简体   繁体   中英

Find all partitions of n of length less-than-or-equal to L

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

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 ni 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM