我不确定是什么问题。我想我可能已经超过了数组限制。
def lcs(arr):
if len(arr) == 0: # arr of length 0
return
sumarr = []
counter = 0
sum = 0
for i in arr:
if arr[i] > 0:
sum = sum + arr[i]
if arr[i] < 0:
sumarr[counter] = sum
counter += 1
print max(sumarr)
我得到的错误是:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in lcs
IndexError: list index out of range
#
我已经修改了一些代码
def lcs(arr):
if len(arr) == 0: # arr of length 0
return
sumarr = []
counter = 0
sum = 0
for i in arr:
if i > 0:
sum = sum + i
if i < 0:
sumarr[counter] = sum
counter += 1
print max(sumarr)
但是我收到了这个错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 13, in lcs
ValueError: max() arg is an empty sequence
我以为我不断更新我的sumarr []。为什么错误告诉我我将空列表传递给max()?
答案 0 :(得分:1)
当你执行for i in arr
时,i
获取数组的元素(一次一个),而不是它们的索引。您希望在示例中将每个arr[i]
替换为i
。
答案 1 :(得分:1)
使用enumerate指向数组的右侧位置:
def lcs(arr):
if len(arr) == 0: # arr of length 0
return
sumarr = []
counter = 0
sum = 0
for count, i in enumerate(arr):
if arr[count] > 0:
sum = sum + arr[i]
if arr[count] < 0:
sumarr[counter] = sum
counter += 1
print max(sumarr)