[英]How can I use recursion on two-tuples to sum up the second values?
假設我有一個元組:
x = (20,400), (10,100), (10,200)
我有一個價值
y = 30
我試圖找到所有相關的第二個值,其 x 中的第一個值加起來小於或等於 y。
所以我的遞歸問題將返回 600,因為它從 20 和 10 中添加了 400 和 200。由於 200 大於與 10 關聯的其他 100,因此它將添加那個。
def recur(x, y):
if len(x) == 0:
return x
else:
#use recursion here but I can't quite figure it out.
recur((10,60), (20,100), (30,200), 50)
# Returns :
300
# Because it adds 20 and 30 since they both add up to 50 and have the
highest numbers associated with them.
這個問題可以遞歸解決,但它可能不是特別有效,當然也不是很優雅。 請注意wrapper
function 如何通過按每對的第二個元素對其進行排序來准備參數,以及稍后如何從recur
的結果中對這些元素求和。
def recur(x, y):
for i, item in enumerate(x):
if item[0] == y:
return [item]
elif item[0] > y:
return []
reduced_set = x[:i] + x[i+1:]
result = recur(reduced_set, y-item[0])
if result:
return [item] + result
return []
def wrapper(x, y):
result = recur(sorted(x, key=lambda x: x[1], reverse=True), y)
return sum(item[1] for item in result)
x = (20,400), (10,100), (10,200)
print(wrapper(x, 30))
x = (10,60), (20,100), (30,200)
print(wrapper(x, 50))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.