Reputation: 9
hello i am a beginner to python and I need help with this issue I have to write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
move_zeros([1, 0, 1, 2, 0, 1, 3]) would return returns [1, 1, 2, 1, 3, 0, 0]
def move_zeros(array):
zeroCount = 0
length = len(array)
for i in range(length):
if array[i] == "0":
zeroCount += 1
array.remove(0)
for i in range(zeroCount):
array.append("0")
return array
Upvotes: 0
Views: 314
Reputation: 2532
To me, the way you are trying to code this is a little bit too complicated so, since we are using Python, I would try to be as pythonic as possible.
I would do something like this:
def move_zeros(array):
array_no_zeros = [i for i in array if i != 0]
zero_count = array.count(0)
zeros_list = [0] * zero_count
return array_no_zeros + zeros_list
result = move_zeros([1, 0, 1, 2, 0, 1, 3])
>>> [1, 1, 2, 1, 3, 0, 0]
Upvotes: 0
Reputation: 90
def move_zeros(array):
zeroCount = 0
for i in range(len(array)):
if array[i] == 0:
zeroCount += 1
for i in range(zeroCount):#you have to call array.remove(0) zeroCount times to remove all zeros
array.remove(0)
for i in range(zeroCount):
array.append(0)
return array
array = [1,0,1,2,1,0,3]
print(move_zeros(array))
Upvotes: 0
Reputation: 71454
The first two problems that jump out are that the indentation is wrong, and that your code is looking for "0"
, not 0
. Let's fix those before we start debugging:
def move_zeros(array):
zeroCount = 0
length = len(array)
for i in range(length):
if array[i] == 0:
zeroCount += 1
array.remove(0)
for i in range(zeroCount):
array.append(0)
return array
That's not enough to make this work, though:
>>> move_zeros([1, 0, 1, 2, 0, 1, 3])
[1, 1, 2, 0, 1, 3, 0, 0]
Looks like we're only removing one zero, but we're appending two! That must be because remove
only removes one instance. An easy fix for that is to do it in a loop:
for _ in range(zeroCount):
array.remove(0)
which now gives us the right answer:
>>> move_zeros([1, 0, 1, 2, 0, 1, 3])
[1, 1, 2, 1, 3, 0, 0]
And we can make the function a little simpler by replacing the for i in range(length)
thing with a call to array.count()
:
def move_zeros(array):
zero_count = array.count(0)
for _ in range(zero_count):
array.remove(0)
for _ in range(zero_count):
array.append(0)
return array
Something to watch out for is that this function doesn't just return
a list with the zeroes moved, it moves them in the original as well. If you wanted to avoid that, a better approach would be to build a brand new list, e.g.:
def move_zeros(array):
return [i for i in array if i != 0] + [i for i in array if i == 0]
Upvotes: 1