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

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.

Sign up to request clarification or add additional context in comments.

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)

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

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.