【问题标题】:Is there an efficient way to find all integer tuples of length 10 that sum to 100有没有一种有效的方法来找到所有长度为 10 且总和为 100 的整数元组
【发布时间】:2022-08-23 17:45:40
【问题描述】:

我正在尝试查找仅包含加到 100 的正整数(允许为 0)的所有元组。我对每个索引的最大值有一些限制。我有包含这些约束的列表最大值

maxs = [3, 9, 14, 21, 21, 35, 31, 49, 42, 38]

到目前为止,我只是在运行这个 10 维嵌套 for 循环

combinations = []
for s1 in range(maxs[0]+1):
    for s2 in range(maxs[1]+1):
        for s3 in range(maxs[2]+1):
            for s4 in range(maxs[3]+1):
                for s5 in range(maxs[4]+1):
                    for s6 in range(maxs[5]+1):
                        for s7 in range(maxs[6]+1):
                            for s8 in range(maxs[7]+1):
                                for s9 in range(maxs[8]+1):
                                    for s10 in range(maxs[9]+1):
                                        if s1 +s2+s3+s4+s5+s6+s7+s8+s9+s10 == 100:
                                            combinations.append([s1,s2,s3,s4,s5,s6,s7,s8,s9,s10]

如果有帮助的话,我知道严格来说少于 10^11 种组合。可能这个问题太大了

谢谢

  • 如果允许 0,那么您应该在列表中包含 0。
  • 0 包括在内。 range(i) 包括 0 到 i-1

标签: python algorithm performance math combinatorics


【解决方案1】:

改用递归函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多