【问题标题】:Getting all combination of calculating X given a list of numbers [closed]在给定数字列表的情况下获取计算 X 的所有组合[关闭]
【发布时间】:2021-04-18 00:29:07
【问题描述】:

相当简单的想法,但在代码中更难(对我来说)。

我想知道有多少组合来计算一个数字 X 给定我可以计算的数字。
这是一个例子:

>>> calculate(5, (1,2,5))
4
>>> calculate(42, (1,2,5,10,20))
271

第一个例子给出 4 因为:

  • 5
  • 2 + 2 + 1
  • 2 + 1 + 1 + 1
  • 1 + 1 + 1 + 1 + 1

    我很确定这可以使用动态编程或递归记忆快速完成,但想不出一种开始整个事情的方法。

    编辑
    我想这样做:Find all combinations of a list of numbers with a given sum 但是由于一些未知的原因,大多数代码都不起作用,而其他代码甚至无法执行我给出的简单示例 5 或 42 之类的数字。

【问题讨论】:

标签: python combinations


【解决方案1】:

您可以使用一个函数在输入列表中找到所需总和的所有除数:

def calculate(v, d, c = []):
   if not v:
      yield tuple(sorted(c))
   elif v > 0:
      vals = [i for i in d if not v%i] #find divisors
      for i in vals:
         for j in range(1, int(v/i)+1):
            #run offset by subtracting the current divisor iteration by the running total "v" 
            yield from calculate(v - (i*j), [x for x in d if x != i], c + ([i]*j))
      if not vals: #no divisors found
         for i in d:
             yield from calculate(v - i, d, c+[i])

print(len(set(calculate(5, (1,2,5)))))
print(len(set(calculate(42, (1,2,5,10,20)))))
print(len(set(calculate(15, (9, 6))))) #example with no divisors

输出:

4
271
1

【讨论】:

    【解决方案2】:

    找到了!一切都在 StackOverflow 上:p
    来自there的代码:

    def subsets_with_sum(lst, target, with_replacement=False):
        x = 0 if with_replacement else 1
        def _a(idx, l, r, t):
            if t == sum(l): r.append(l)
            elif t < sum(l): return
            for u in range(idx, len(lst)):
                _a(u + x, l + [lst[u]], r, t)
            return r
        return _a(0, [], [], target)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      相关资源
      最近更新 更多