What's wrong with my python codes

  • 0

    class Solution(object):
    def moveZeroes(self, nums):
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.

        numOfZero = nums.count(0)
        n = len(nums)
        if numOfZero == len(nums) or numOfZero == 0:
        for i in range(n):
            if nums[i] == 0:
                del nums[i]
        for i in range(numOfZero):

  • 0

    Modifying a list while iterating over it. This is what called accidental-deletion-of-a-list-item-while-iterating-over-it bug. You can try nums[:] = [n for n in nums if n] to move zeros from nums

  • 0
    This post is deleted!

  • 0

    yes, it is not suitable to delete the element in the iterating. I use del after the iterating.

    count_zero = nums.count(0)
    index = 0
    for i in range(0,len(nums)):
        if nums[i] != 0:
            nums[index] = nums[i]
            index = index + 1
    del nums[index:]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.