0

我不确定出了什么问题。我想我可能已经超过了数组限制。

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

4

2 回答 2

1

当你这样做时for i in arri获取数组的元素(一次一个),而不是它们的索引。您在示例中想要的是将每个替换arr[i]i.

于 2013-08-10T13:02:31.437 回答
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)
于 2013-08-10T13:03:06.387 回答