简体   繁体   English

索引超出范围 | Python

[英]Index out of range | Python

I am attempting the TwoSum Question using python and have tried the two pointer method essentially having a pointer at the beginning and end of the array, when the sum of the two indexes is greater than the value where are looking for it decrements the ending pointer one index less and if the sum is less than it increments the beginning pointer by 1. I keep getting an index out of range error and would like to know why it happens.我正在尝试使用 python 的 TwoSum 问题,并尝试了两个指针方法,基本上在数组的开头和结尾都有一个指针,当两个索引的总和大于正在寻找的值时,它会减少结束指针一个index less 并且如果总和小于它将开始指针增加 1。我不断收到 index out of range 错误,并想知道它为什么会发生。 I stepped through my code and everything seems to make sense and my test case passes but it gives me an out of range error when I get a list like this:我逐步浏览了我的代码,一切似乎都有意义,我的测试用例通过了,但是当我得到这样的列表时,它给了我一个超出范围的错误:

  [-1,-2,-3,-4,-5] and the target being -8
  the goal is to output index positions [2,4] using the two pointer technique

Here is my code:这是我的代码:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

        stack = list()

        n = len(nums)
        j = (len(nums)-1)
        i = 0

        while i < n:

            tempSum = nums[i] + nums[j]

            if tempSum == target:
                stack.append(i)
                stack.append(j)
                break
            if tempSum > target:
                j-=1
            else:
                i+=1
        return stack

The error happens due to the logic you have built in your while loop.该错误是由于您在 while 循环中构建的逻辑而发生的。 Whenever tempSum is larger than target, you subtract 1 from j .只要tempSum大于目标,就从j中减去1 When working with negative numbers, this means that your loop will continue reducing j until it reaches j=-6 , at which point it will produce an out of range error.使用负数时,这意味着您的循环将继续减少j直到达到j=-6 ,此时它将产生超出范围的错误。

Try taking the absolute value of tempSum and target within your if statement, then the evaluation will work in case of negative numbers as well.尝试在 if 语句中tempSumtarget的绝对值,那么在负数的情况下也可以进行评估。

if abs(tempSum) > abs(target):
    j-=1
else:
    i+=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM