Thursday, February 29, 2024
HomeSoftware EngineeringThe right way to Transfer Zeros to the Finish in Python

# The right way to Transfer Zeros to the Finish in Python

## The problem#

Write an algorithm that takes an array and strikes the entire zeros to the top, preserving the order of the opposite components.

``````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 sort(x) isn't 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]
``````

## Check circumstances to validate our answer#

``````import check
from answer import move_zeros

@check.it("Fundamental 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