I'm not sure what's wrong. I assume I have surpassed an array limit perhaps.
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)
The error I get is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in lcs
IndexError: list index out of range
#
I've modded the code a bit
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)
However I'm getting this error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 13, in lcs
ValueError: max() arg is an empty sequence
I thought I was constantly updating my sumarr[]. How come the error is telling me that I am passing an empty list into max()?
LiondancerLiondancer
asked Aug 10, 2013 at 13:00
2 Answers 2
When you do for i in arr
, i
gets the elements of the array (one at a time), not their indices. What you want in your example is to replace each arr[i]
with i
.
answered Aug 10, 2013 at 13:02
Comments
Use enumerate to go point to right position of the array:
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)
answered Aug 10, 2013 at 13:03
1 Comment
shx2
What's the point of using
enumerate
if the count
variable is not used? (should have i
instead of arr[count]
)lang-py