简体   繁体   中英

combination of number using specific value limit as sum of combinations

Are there any tools in python to generate these combinations:

a=200
b=100

limit=500

combinations are:

200,200,100  sum(200+200+100)<=500
200,100,100,100 sum(200,100,100,100)<=500  
>>> 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)]

Here is the function form:

>>> 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)]

Note: This solution is not fully optimized, since it generates every possible combination, continuing to generate longer combinations even when the shorter ones exceed the limit.

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