我尝试将CLRS算法简介中给出的Maximum-Subarray问题的伪代码转换为Python中的完整工作代码。
代码:
def cross(A,low,mid,high):
left_sum = -float("inf")
s = 0
i = mid
while (i >= low):
s = s + A[i]
if s > left_sum:
left_sum = s
max_left = i
i = i - 1
right_sum = -float("inf")
s = 0
j = mid + 1
while (j < high):
s = s + A[j]
if s > right_sum:
right_sum = s
max_right = j
j = j + 1
return (max_left,max_right,left_sum+right_sum)
def maxSubarray(A,low,high):
if high == low: return (low,high,A[low])
else:
mid = (low+high)/2
(left_low,left_high,left_sum) = maxSubarray(A,low,mid)
(right_low,right_high,right_sum) = maxSubarray(A,mid+1,high)
(cross_low,cross_high,cross_sum) = cross(A,low,mid,high)
if (left_sum >= right_sum & left_sum >= cross_sum):return (left_low,left_high,left_sum)
elif (right_sum >= left_sum & right_sum >= cross_sum):return (right_low,right_high,right_sum)
else: return (cross_low,cross_high,cross_sum)
t = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print maxSubarray(t,0,16)
当我尝试跑步时,我收到此错误。
错误:
Traceback (most recent call last):
File "/home/suyash/Downloads/python/max_subarray.py", line 64, in <module>
print maxSubarray(t,0,16)
File "/home/suyash/Downloads/python/max_subarray.py", line 49, in maxSubarray
(left_low,left_high,left_sum) = maxSubarray(A,low,mid)
File "/home/suyash/Downloads/python/max_subarray.py", line 49, in maxSubarray
(left_low,left_high,left_sum) = maxSubarray(A,low,mid)
File "/home/suyash/Downloads/python/max_subarray.py", line 49, in maxSubarray
(left_low,left_high,left_sum) = maxSubarray(A,low,mid)
File "/home/suyash/Downloads/python/max_subarray.py", line 49, in maxSubarray
(left_low,left_high,left_sum) = maxSubarray(A,low,mid)
File "/home/suyash/Downloads/python/max_subarray.py", line 53, in maxSubarray
(cross_low,cross_high,cross_sum) = cross(A,low,mid,high)
File "/home/suyash/Downloads/python/max_subarray.py", line 39, in cross
return (max_left,max_right,left_sum+right_sum)
UnboundLocalError: local variable 'max_right' referenced before assignment
我该如何解决这个问题?我哪里出错?
答案 0 :(得分:1)
两个非常小的错误:
t
的长度为16.这意味着最后一个索引为15.因此请致电maxSubarray(t,0,15)
而不是maxSubarray(t,0,16)
while (j <= high)
。循环到j<= high
直到j<high
同样通过这两项修复,您无需将任何默认值设置为max_right
或max_right
。 <{1}}任何while
条件在每次递归调用中始终为True。
演示:
if
答案 1 :(得分:0)
你忘了考虑边界条件。
当通常成功的条件突然失败时,可能会出现一个问题,使变量保持未绑定状态。无论如何,您都需要确保变量具有合理的默认值。
答案 2 :(得分:0)
您只需在max_right
循环内的if
语句中指定while
,这意味着如果您收到异常,则s > right_sum
或j < high
是从不是真的:
while (j < high):
s = s + A[j]
if s > right_sum:
right_sum = s
max_right = j
j = j + 1
您应该max_right
while
一个默认值在之外max_right = high
循环; {{1}}在这里是合适的。