0

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()?

asked Aug 10, 2013 at 13:00

2 Answers 2

1

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

1

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

What's the point of using enumerate if the count variable is not used? (should have i instead of arr[count])

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.