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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more