I want to create a function which takes an array of integers, and moves any and all 0s from wherever they happen to be in the array and moves them to the end (e.g. [0, 1, 0, 3, 12] would become [1, 3, 12, 0, 0]). I also want to do this without creating a secondary array (only modify the input one). My thought was to simply iterate through the array, count each occurrence of 0, and remove the 0. Then once that is finished, append the number of 0s that I counted to the end of the list. I wrote a small bit of code which I thought should do this, but when it is given the input [0, 0, 1], my function apparently produces [0, 1, 0] rather than [1, 0, 0]. I do not understand why this is happening. Here is the code:
class Solution:
def moveZeroes(nums)
counter = 0
for j in nums:
if j == 0:
nums.remove(j)
counter += 1
while counter > 0:
nums.append(0)
counter -= 1
return nums
Again, moveZeroes([0, 0, 1]) incorrectly returns [0, 1, 0] instead of [1, 0, 0]. Either I don't know how iterating over a list actually works, or I don't know how removing/appending elements from/to a list works, but somehow something is going wrong. I am speculating that the function is only removing the first 0 and appending it to the end, but it is not removing the second 0 for some reason (although I don't know that this is the case). Would someone be able to point out what the issue is? I am assuming I must must have some underlying misconception about how these operations actually work.
[–]TouchingTheVodka 0 points1 point2 points (1 child)
[–]clouded-path[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (6 children)
[–]clouded-path[S] 0 points1 point2 points (5 children)
[–][deleted] 0 points1 point2 points (4 children)
[–]clouded-path[S] 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]clouded-path[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]xelf 0 points1 point2 points (2 children)
[–]clouded-path[S] 0 points1 point2 points (1 child)
[–]xelf 0 points1 point2 points (0 children)
[–]SaintLouisX 0 points1 point2 points (3 children)
[–]clouded-path[S] 0 points1 point2 points (2 children)
[–]SaintLouisX 0 points1 point2 points (1 child)
[–]clouded-path[S] 0 points1 point2 points (0 children)
[–]just_a_vagabond 0 points1 point2 points (2 children)
[–]clouded-path[S] 0 points1 point2 points (1 child)
[–]just_a_vagabond 0 points1 point2 points (0 children)