DEV Community

Cover image for Python 🐍 challenge_28βš”οΈ
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on β€’ Edited on

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay