How to Move Zeros to the End in Python

The challenge

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]) # returns [1, 1, 2, 1, 3, 0, 0]
Code language: Python (python)

The solution in Python code

Option 1:

def move_zeros(arr): l = [i for i in arr if isinstance(i, bool) or i!=0] return l+[0]*(len(arr)-len(l))
Code language: Python (python)

Option 2:

def move_zeros(array): return sorted(array, key=lambda x: x==0 and type(x) is not bool)
Code language: Python (python)

Option 3:

def move_zeros(array): return [a for a in array if isinstance(a, bool) or a != 0] + [a for a in array if not isinstance(a, bool) and a == 0]
Code language: Python (python)

Test cases to validate our solution

import test from solution import move_zeros @test.it("Basic tests") test.assert_equals(move_zeros( [1, 2, 0, 1, 0, 1, 0, 3, 0, 1]), [1, 2, 1, 1, 3, 1, 0, 0, 0, 0]) test.assert_equals(move_zeros( [9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]), [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) test.assert_equals(move_zeros([0, 0]), [0, 0]) test.assert_equals(move_zeros([0]), [0]) test.assert_equals(move_zeros([]), [])
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments