![](/img/trans.png)
[英]How can I find the sum of numbers in a list that are not adjacent to a given number?
[英]check Recursively if i can create a sum of given number from a list of numbers
我得到一個數字和一個清單。 我必須找到列表中數字的最大數量,才能得出給定數字的總和。
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)
預期輸出:4 -- 最大的是 1 + 2 + 2 + 1
實際輸出:3
您可以通過遞歸嘗試列表中元素的不同組合來解決此問題(動態編程)。 像這樣。
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
這是您問題的答案。 請讓其他人解釋為什么它有效,因為我只是理解這一點,使其適用於您的答案:
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)
摘自:
https://docs.python.org/3/library/itertools.html#itertools-recipes
希望這可以幫助 :)
免責聲明:有效的python3代碼。 不確定更改打印以刪除括號是否有效,但您可以嘗試:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.