我在 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/