简体   繁体   English

总和为另一个特定数字的自然数组合

[英]Natural numbers combination that sum to another specific number

If i have two natural numbers, "k" and "n".如果我有两个自然数,“k”和“n”。 How can i show all combinations in "k" parts that sum to "n"?我怎样才能显示总和为“n”的“k”部分中的所有组合? I tried this code, but i'd like do exclude the sum with zero from the output tuples.我试过这段代码,但我想从 output 元组中排除零的总和。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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