Thursday, February 23, 2023
HomeSoftware EngineeringFind out how to Transfer Zeros to the Finish in Python

# Find out 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 components.

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

## The answer in Python code#

Choice 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))
``````

Choice 2:

``````def move_zeros(array):
return sorted(array, key=lambda x: x==0 and sort(x) will not be bool)
``````

Choice 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 circumstances to validate our resolution#

``````import check
from resolution import move_zeros

@check.it("Primary assessments")

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