我一次又一次地查看了这段代码,将其与在线其他示例进行了比较,我似乎无法找到问题所在。这是一个分而治之的,递归的最大子问题。也许它是一个小的语法错误,也许它是一个明显愚蠢的东西,我似乎无法解决它。我不断收到一条错误消息,提示" RuntimeError:超出最大递归深度" 。关于我可能做错什么的任何指导或提示?我是Python的新手,所以任何事情都有帮助,谢谢你对我的支持。
import math
def divConHelper(array, first, center, last):
sumRight = 0
sumLeft = 0
# Determine crossover max toward left
currentLTotal = 0
for i in range(center, first, -1):
#Add values to sum one by one
currentLTotal += array[i]
#if the total is greater than the sumLeft, replace
if currentLTotal > sumLeft:
sumLeft = currentLTotal
leftIndexMax = i
# Determine crossover max toward right
currentRTotal=0
for j in range(center+1, last):
#Incrementally add values to sum
currentRTotal += array[j]
#if the rightTotal is greater than the sumRight, replace
if currentRTotal > sumRight:
sumRight = currentRTotal
rightIndexMax = j
bothTotal = rightTotal+leftTotal
return(leftIndexMax, rightIndexMax, bothTotal)
#return(bothTotal)
def divConMaxSub(array, first, last):
first = 0
last = len(array)-1
# If no values in the file
if len(array) == 0:
print("No values in file")
return
# If only one value in the file
elif len(array) == 1:
print("Only one value in file")
return array[0]
# If more than 1 value in the file...
else:
# Find middle value index by halving the last index
center = math.floor((first+last)/2)
# Make recursive calls inside max() function, including crossovers
# to find the max subarray & return the result
return max(divConMaxSub(array, first, center), divConMaxSub(array, center+1, last), divConHelper(array, first, center, last))
#for test purposes
arrayin = [1, 2, 4, -1, 4, -10]
maxsum= divConMaxSub(arrayin, 0, len(arrayin)-1)