gpt4 book ai didi

python - 使用特定值限制作为组合总和的数字组合

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:36 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于python - 使用特定值限制作为组合总和的数字组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com