[英]Generative recursion to find the sublist with the maximum sum
我正在嘗試解決Python中的生成遞歸問題。 問題是:
我必須遵循給定的算法來解決find_max:
我嘗試了以下方法:
def find_max(L):
length = len(L)
mid_index = length/2
if length == 1:
return L[0]
else:
left = find_max(L[0:(length/2)])
right = find_max(L[(length/2):length])
max_subset = max(left,right,left+right)
return max_subset
這樣就可以解決長度為2的列表。如何將其擴展為適用於具有更多元素的列表?
您沒有考慮以下事項:
L
為[2, -5, 3]
,則在第一次遞歸中, left + right
將產生5。 def find_max(L):
length = len(L)
mid_index = length/2
if length == 0:
return 0
elif length == 1:
return max(L[0], 0)
left = find_max(L[:mid_index])
right = find_max(L[mid_index:])
left_half = right_half = 0
# to the left
accum = 0
for x in L[mid_index-1::-1]:
accum += x
left_half = max(left_half, accum)
# to the right
accum = 0
for x in L[mid_index:]:
accum += x
right_half = max(right_half, accum)
return max(left, right, left_half + right_half)
assert find_max([]) == 0
assert find_max([-1]) == 0
assert find_max([1, 2, 3]) == 6
assert find_max([2, -5, 3]) == 3
assert find_max([-5, 1, 4, -2, 2, -1, 2, -3, 1, -3, 4]) == 6
沒有for循環:
def sum_max(L, accum=0, max_value=0):
if not L:
return max_value
accum += L[0]
return sum_max(L[1:], accum, max(max_value, accum))
def find_max(L):
...
left_half = sum_max(L[mid_index-1::-1])
right_half = sum_max(L[mid_index:])
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.