python - IndexError : list index out of range in"if. ..否则...”

标签 python python-3.x python-3.7

我在 leetcode 中练习了“从排序数组中删除重复项”的测试。一切都很好,但是当我测试 input[1,1] 时,它失败了:

IndexError: list index out of range

我可以知道为什么吗?(​​我已经有了正确的解决方案,但我仍然想知道这个错误。)

这是我的代码:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        index_o=0
        i=1
        while i <len(nums):   
              if nums[index_o]==nums[i]:
                  nums.remove(nums[i])
                  index_o-=1
                  i-=1
                  print("nums[index_o]:",nums[index_o])
                  print("index_o:",index_o)
                  print("nums[i]:",nums[i])
                  print("i:",i)
                  print("nums:",nums)
              else:
                  index_o+=1
                  i+=1
        return len(nums)

n=[1,1]
a=Solution()
print(a.removeDuplicates(n))
print(n)

这是结果:

f:leetcode>python 190626.py
nums[index_o]: 1
index_o: -1
nums[i]: 1
i: 0
nums: [1]
Traceback (most recent call last):
  File "190626.py", line 228, in <module>
    print(a.removeDuplicates(n))
  File "190626.py", line 217, in removeDuplicates
    print("nums[index_o]:",nums[index_o])
IndexError: list index out of range

这是一个正确的解决方案:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        index_o=0
        i=1
        while i <len(nums): 
              if nums[index_o]==nums[i]:
                  nums.remove(nums[index_o])
              else:
                  index_o+=1
                  i+=1
        return len(nums)

最佳答案

在循环的第三次迭代中,您有变量 i=-1且 n=[]。您的代码首先输入 if-1 < 0等于 True .*

此时,您尝试使用变量 index_o 访问数组,即-2。由于数组为空,因此 n[-2] 返回 IndexError: list index out of range错误。

对您的代码的一些评论:
- 该算法没有做它应该做的事情,但我可以理解你的想法。
- 为什么删除重复函数会返回输出数组的长度,而不是数组本身?
- 要测试该算法,您可以使用 set()内置的,将从数组中删除重复项。然后你就可以比较它们。
- 开发算法时,请始终通过打印值来进行调试,正如@Mark-meyer 在评论中所建议的那样。

*我没有在本地运行你的算法并进行调试,我只是从头跟踪它。因此某些值可能会相差一。

关于python - IndexError : list index out of range in"if. ..否则...”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56879339/

相关文章:

python - 使用多索引创建一个包含列名称的新 csv 文件

python - Python中的箭头动画

python - Django 和 weasyprint,合并 pdf

python - 编写简洁、灵活且易于维护的用户输入提示

python - 如何使用十进制数/数据与 python 3 检查相关性

python - 太空侵略者 : Loading Images

python - 重用数据类类型提示

python-3.x - 如何注释返回 self 的 Python3 方法?

python - 两行 Python 代码导致 3 个执行 block

python - AWS Lambda 错误消息 "Unable to import module ' lambda_function' : No module named 'lambda_function' ",