Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort the people using a single line

I crossed by this question on LeetCode: https://leetcode.com/problems/sort-the-people/description

This is a VERY simple question, where the idea is to sort "a list of people" by their given "heights". After a few seconds I came out with the following code:

# Input: names = ["Mary","John","Emma"], heights = [180,165,170]
# Output: ["Mary","Emma","John"]

def sortPeople(names: List[str], heights: List[int]) -> List[str]:
        d = {heights[i]:names[i] for i in range(len(names))}
        return [d[h] for h in sorted(d.keys(), reverse=True)]

I was wondering if we can use only one line here, without repeating code and/or repeating calculations.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

names = ["Mary","John","Emma"]
heights = [180,165,170]

[names[i] for i in sorted(range(len(names)), key=lambda x: heights[x], reverse=True)]
>>> ['Mary', 'Emma', 'John']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading