DEV Community

Bernice Waweru
Bernice Waweru

Posted on • Edited on

CodeWars Kata: Moving Zeros To The End

As a junior developer applying for jobs, I have found myself needing to brush up on my data structures and algorithms knowledge. I decided to try out some challenges on CodeWars, which I feel is beginner-friendly compared to other sites.

On CodeWars, the challenges(Katas) are categorized depending on the difficulty, with 8kyu being the easiest and 1Kyu being the hardest.
In this challenge;

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

move_zeros([1, 0, 1, 2, 0, 1, 3]) # returns [1, 1, 2, 1, 3, 0, 0]
Enter fullscreen mode Exit fullscreen mode

Approach
Find all zeros in the list and move them to the end.
One way to implement this would be to initialize a new list, loop through the original list to find zeros, and append them to the new list. Use the extend() method to add the zeros to the end of the list.

def move_zeros(lst):
    newarr =[]
    zeroarr=[]
    for i in lst:
        if i != 0 or type(i)== bool :
            newarr.append(i)
        else:
            zeroarr.append(i)

    newarr.extend(zeroarr)
    return(newarr)
Enter fullscreen mode Exit fullscreen mode

Use Lambda
Although the solution above gets the job done, there's a more pythonic way to do it using the lambda function. Read more about the lambda function here.

Syntax: lambda argument(s): expression

def move_zeros(lst):
    return sorted(lst, key=lambda x: x==0 and type(x) is not bool)
Enter fullscreen mode Exit fullscreen mode

sorted() has a key parameter to specify a function to be called on each element.
The lambda function is an anonymous function that, when used with sorted, returns the list with the zeros at the end.
This post can clarify how sorted and the lambda function work under the hood.

Top comments (0)