HomeSoftware EngineeringLearn how to Transfer Zeros to the Finish in Python

Learn how to Transfer Zeros to the Finish in Python


The problem

Write an algorithm that takes an array and strikes all the zeros to the tip, preserving the order of the opposite parts.

move_zeros([1, 0, 1, 2, 0, 1, 3]) # returns [1, 1, 2, 1, 3, 0, 0]

The answer in Python code

Possibility 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))

Possibility 2:

def move_zeros(array):
    return sorted(array, key=lambda x: x==0 and kind(x) shouldn't be bool)

Possibility 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]

Take a look at instances to validate our answer

import check
from answer import move_zeros

@check.it("Primary checks")

check.assert_equals(move_zeros(
    [1, 2, 0, 1, 0, 1, 0, 3, 0, 1]),
    [1, 2, 1, 1, 3, 1, 0, 0, 0, 0])
check.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])
check.assert_equals(move_zeros([0, 0]), [0, 0])
check.assert_equals(move_zeros([0]), [0])
check.assert_equals(move_zeros([]), [])
RELATED ARTICLES

Most Popular

Recent Comments