Sort by Height Python Practice Problem

Published by Brandon on

Today we are going to take a look at another CodeSignal Practice Problem called Sort by Height.

Here is the problem description:

Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!

Example

For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
solution(a) = [-1, 150, 160, 170, -1, -1, 180, 190].

I wanted to show my solution first and then we can take a look at the best user submitted solution!

My Solution

The first thing I wanted to do was create a new list without -1’s in it. To do that, a simple list comprehension sounded good. Then, I sorted that list using the sorted function and set variable r equal to that new sorted list.

The next thing I needed to do was insert those -1’s back in the same place that they were before (same index, that is). To do that, I grab the indexes where there was a -1 before and insert a -1 back into that index with the list insert() method.

So, here’s my full solution:

def solution(a):
    # Sort a new list without -1's in it. 
    r = sorted ([x for x in a if x != -1])
    # Go through that new list and insert into it where the -1 was previously
    for x in range(len(a)):
        if a[x] == -1:
            r.insert(x, -1)
    return r

The Best Solution

The best solution wasn’t too far off from mine. The only big difference between the two is that they used an enumerate function to loop through to get the index value of where the -1’s were beforehand.

def solution(a):

    l = sorted([i for i in a if i > 0])
    for n,i in enumerate(a):
        if i == -1:
            l.insert(n,i)
    return l
        

Thanks for checking out my article, and if you want more content, feel free to check out my YouTube Channel!

Categories: Python

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *