[英]check Recursively if i can create a sum of given number from a list of numbers
I get a number and a list.我得到一个数字和一个清单。 I must find the maximum number of numbers in the list to give me the sum of the given number.
我必须找到列表中数字的最大数量,才能得出给定数字的总和。
def calc_max_baggage (weights, W):
if W==0: # if W == 0 or weights == []: is the same.
return 0
elif weights==[]:
return 0
elif sum(weights)==W:
return len(weights)
elif weights[-1]==W:
return 1
elif W==0:
return 1
option1 = 0+calc_max_baggage(weights[:-1], W)
option2 = 0+calc_max_baggage(weights[1:], W)
return max(option2,option1)
print calc_max_baggage([3,1,2,3,2,1],6)
Expected output: 4 -- the largest is 1 + 2 + 2 + 1预期输出:4 -- 最大的是 1 + 2 + 2 + 1
Actual output: 3实际输出:3
You can solve this by recursively trying different combinations of elements from the list (Dynamic Programming).您可以通过递归尝试列表中元素的不同组合来解决此问题(动态编程)。 like this.
像这样。
def calc_max_baggage(li, tot, current_bagage=0, max_baggage=0):
if tot == 0 or len(li)==0: return current_bagage
if tot < 0: return 0
for i in range(len(li)):
temp = calc_max_baggage(li[:i] + li[i+1:], tot-li[i], current_bagage+1)
if temp > max_baggage:
max_baggage = temp
return max_baggage
Here is the answer to your question.这是您问题的答案。 Please ask someone else to explain why it works because I only understood this to make it work for your answer:
请让其他人解释为什么它有效,因为我只是理解这一点,使其适用于您的答案:
from itertools import chain, combinations
weights = (3, 1, 2, 3, 2, 1)
W = 6
# weights = (3, 1, 2, 3, 2, 1) / w = 6 / Output: 4
# weights = [1, 1, 1] / w = 2 / Output: 2
# weights = (1, 1, 1) / w = 7 / Output: 3
# weights = [4,2,1,3] / w = 5 / Output: 2
# weights = [5] / w =5 / Output: 1
def powerset(iterable):
"""
:param iterable: the iterable you want to find all combinations for
:return: each combination of the iterables in this example:
:example:
weights = (3, 1, 2, 3, 2, 1)
w = len(weights)
powersets = []
for x in powerset(weights):
if sum(x) == w:
print(x)
powersets.append(len(x))
Output >>>
(3, 3)
(3, 1, 2)
(3, 1, 2)
(3, 2, 1)
(3, 2, 1)
(1, 2, 3)
(1, 3, 2)
(2, 3, 1)
(3, 2, 1)
(1, 2, 2, 1)
4
"""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
def calc_max_baggage(weights, W):
powersets = []
# for x in powerset(weights):
# if sum(x) <= w:
# print(x)
# powersets.append(len(x))
# Because you said no for loops somewhere:
powersets = [len(x) for x in powerset(weights) if sum(x) <= W]
print(max(powersets))
calc_max_baggage(weights, W)
Which was lifted from:摘自:
https://docs.python.org/3/library/itertools.html#itertools-recipes https://docs.python.org/3/library/itertools.html#itertools-recipes
Hope this helps :)希望这可以帮助 :)
Disclaimer: valid python3 code.免责声明:有效的python3代码。 Unsure if changing print to remove parentheses will work but you can try :)
不确定更改打印以删除括号是否有效,但您可以尝试:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.