![](/img/trans.png)
[英]Recursive function for finding combinations without hitting the built-in limit in python
[英]How to limit Python recursive combinations?
我当前正在尝试解决如何使这段代码迭代下面等于1200的数字的不同组合。这很好,但是我希望代码限制它探索的数字并仅用5个不同的数字打印组合。
例如70、260、280、290、300 = 1200,使用5个数字。 我只想要这些组合。
例如10、20、30、40、110、120、160、190、240、280 = 1200 = 1200,使用10个数字。 我不希望组合少于5或大于5。
我对python不太了解,我觉得这很简单,但是由于我有限的编码知识,我陷入了困境。
#!/usr/local/bin/python
from itertools import combinations
def find_sum_in_list(numbers, target):
results = []
for x in range(len(numbers)):
results.extend(
[
combo for combo in combinations(numbers ,x)
if sum(combo) == target
]
)
print results
if __name__ == "__main__":
find_sum_in_list([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300], 1200)
谢谢你的帮助。 非常感激。
我认为组合第二个参数是要组合的项目数。 尝试传递5而不是x
实际上,您几乎拥有所需的东西。 列表理解中的两行几乎所有内容,除了@Eric所说的使用'5'代替'x'之外。 如果使用过滤器滤除所有没有正确总和的组合,那么最终结果是:
from itertools import combinations
def find_sum_in_list(numbers, target):
return filter(lambda x: sum(x) == target, combinations(numbers, 5))
if __name__ == '__main__':
print find_sum_in_list(range(10, 310, 10), 1200)
filter具有接受列表中每个元素并返回true或false的函数。 我已经传递给它一个匿名函数,该函数仅在列表求和到目标时才返回true。
我还使用range来生成您的数字列表,方法是从10到310乘以10。range排除了最后一个元素。
嗯,它的递归性不比您的代码少,但我认为它确实可以满足您的要求。
import itertools
target_list = [
10, 20, 30, 40, 50, 60, 70, 80,
90, 100, 110, 120, 130, 140, 150,
160, 170, 180, 190, 200, 210, 220,
230, 240, 250, 260, 270, 280, 290, 300
]
target_sum = 1200
def find_sum(target_list, num_elem, target_sum):
combinations = itertools.combinations(target_list, num_elem)
for comb in combinations:
if sum(comb) == target_sum:
print comb
find_sum(target_list, 5, target_sum)
您走在正确的道路上,但我认为您无需进行递归操作。 我认为这可行。
from itertools import combinations
def find_sum_in_list(numbers, target, comboSize):
results = []
for combo in combinations(numbers, comboSize):
if sum(combo) == target:
results.append(combo)
return results
if __name__ == "__main__":
numbers = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300]
total = 1200
comboSize = 5
print find_sum_in_list(numbers, total, comboSize)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.