简体   繁体   中英

Natural numbers combination that sum to another specific number

If i have two natural numbers, "k" and "n". How can i show all combinations in "k" parts that sum to "n"? I tried this code, but i'd like do exclude the sum with zero from the output tuples.

def compositions(k, n):
    if k == 1:
        return [(n,)]

    comp = []
    for i in range(n + 1):
        for t in compositions(k - 1, n - i):
            comp.append((i,) + t)
    return comp

Thank you!

If you want the same outputs but without outputs that include zero, you could do the following.

def compositions(k, n):
    
    if n==0:
        return []
    
    if k == 1:
        return [(n,)]

    comp = []
    for i in range(1,n + 1):
        for t in compositions(k - 1, n - i):
            comp.append((i,) + t)
    return comp

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