【问题标题】:combination of number using specific value limit as sum of combinations使用特定值限制作为组合总和的数字组合
【发布时间】:2012-06-07 20:20:17
【问题描述】:

python中有没有工具可以生成这些组合:

a=200
b=100

limit=500

组合是:

200,200,100  sum(200+200+100)<=500
200,100,100,100 sum(200,100,100,100)<=500  

【问题讨论】:

  • 是 100,100,100,100,100 (0*a + 5*b) 也是有效结果吗?
  • 我认为this question 有点相关。

标签: python


【解决方案1】:
>>> from itertools import product
>>> a = 200
>>> b = 100
>>> [x for i in range(1, limit/min((a,b))+1) # Py 2 use xrange for more efficiency
       for x in product((a,b), repeat=i)
       if sum(x) <= limit]
[(200,), (100,), (200, 200), (200, 100), (100, 200), (100, 100), (200, 200, 100), 
 (200, 100, 200), (200, 100, 100), (100, 200, 200), (100, 200, 100), 
 (100, 100, 200), (100, 100, 100), (200, 100, 100, 100), (100, 200, 100, 100), 
 (100, 100, 200, 100), (100, 100, 100, 200), (100, 100, 100, 100), 
 (100, 100, 100, 100, 100)]

函数形式如下:

>>> def combos(nums,limit):
        return [x for i in range(1, limit/min(nums)+1) 
                  for x in product(nums,repeat=i)
                  if sum(x) <= limit]

>>> combos(nums=(200,300,400),limit=700)
[(200,), (300,), (400,), (200, 200), (200, 300), (200, 400), (300, 200),
 (300, 300), (300, 400), (400, 200), (400, 300), (200, 200, 200), 
 (200, 200, 300), (200, 300, 200), (300, 200, 200)]

注意:此解决方案并未完全优化,因为它会生成所有可能的组合,即使较短的组合超过限制,也会继续生成较长的组合。

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多