DEV Community

Cover image for Python ๐Ÿ challenge_28โš”๏ธ
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on • Edited on

Python ๐Ÿ challenge_28โš”๏ธ

Moving Zeros To The End

  • Write an algorithm that takes an array and moves all of the zeros to the end preserving the order of the other elements.

Examples:

move_zeros([1, 0, 1, 2, 0, 1, 3]) => returns [1, 1, 2, 1, 3, 0, 0]

Enter fullscreen mode Exit fullscreen mode
Task URL: Link

My Solution:

def move_zeros(array):
    zeros = [zero for zero in array if zero == 0]
    new_array = [number for number in array if number != 0]
    new_array.extend(zeros)
    return new_array
Enter fullscreen mode Exit fullscreen mode

Another solution

def move_zeros(arr):
    l = [i for i in arr if isinstance(i, bool) or i != 0]
    return l+[0] * (len(arr)-len(l))
Enter fullscreen mode Exit fullscreen mode

Code Snapshot:

Image description

Learn Python

Python top free courses from Coursera๐Ÿ๐Ÿ’ฏ๐Ÿš€

๐ŸŽฅ

Connect with Me ๐Ÿ˜Š

๐Ÿ”— Links

linkedin

twitter

Top comments (0)