python--算出数组中的重复项

在这道题中,涉及到了之前就一直存在的一个错误提醒:IndexError: list index out of range,整好存在这个题,找到了问题所在。

IndexError: list index out of range

正确答案

def removeDuplicates(nums):
    a = len(nums)
    for i in range(a - 1):
        if nums[a - i - 1] == nums[a - i - 2]:
            nums.pop(a - i - 1)
            print(i, nums, len(nums))
        else:
            print(i, nums)
    print(len(nums))

removeDuplicates(nums=[0, 0, 1, 1, 1, 2, 2, 3, 3, 4])

这里循环的部分针对数组采用倒序的方式,查看相邻两个元素是否相等。
从输出可以看出:

0 [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
1 [0, 0, 1, 1, 1, 2, 2, 3, 4] 9
2 [0, 0, 1, 1, 1, 2, 2, 3, 4]
3 [0, 0, 1, 1, 1, 2, 3, 4] 8
4 [0, 0, 1, 1, 1, 2, 3, 4]
5 [0, 0, 1, 1, 2, 3, 4] 7
6 [0, 0, 1, 2, 3, 4] 6
7 [0, 0, 1, 2, 3, 4]
8 [0, 1, 2, 3, 4] 5
5

1、在删除元素的过程中,数组nums已经发生了变化。
2、举个例子,当i=7时,接着要判断nums[2]==nums[1],那么这里后面的8个数已经比较过了,哪怕后面的数都相同,nums[3]=nums[2],删除nums[2]之后,整个数组剩下了三个元素,nums的index不会超出范围,因为最先开始排序比较的也是nums[2]逐次和前面的数进行比较。

错误答案:

def removeDuplicates(nums):
    a = len(nums)
    for i in range(a - 1):
        if nums[i] == nums[i + 1]:
            nums.pop(i)
            print(i, nums, len(nums))
        else:
            print(i, nums)
    return len(nums)
removeDuplicates(nums=[0, 0, 1, 1, 1, 2, 2, 3, 3, 4])

输出结果为:

0 [0, 1, 1, 1, 2, 2, 3, 3, 4] 9
1 [0, 1, 1, 2, 2, 3, 3, 4] 8
2 [0, 1, 1, 2, 2, 3, 3, 4]
3 [0, 1, 1, 2, 3, 3, 4] 7
4 [0, 1, 1, 2, 3, 4] 6

并且提示:

IndexError: list index out of range

就是因为此时数组长度为6,那么在比较nums[5]==nums[6]时,超出了数组大小。所以会出现错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>