What's wrong with my python codes


  • 0
    W

    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:
            return
        for i in range(n):
            if nums[i] == 0:
                del nums[i]
        for i in range(numOfZero):
            nums.append(0)

  • 0
    L

    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
    L
    This post is deleted!

  • 0
    L

    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:]
    nums.extend([0]*count_zero)

Log in to reply
 

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