Sort the people using a single line

92 Views Asked by At

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.

4

There are 4 best solutions below

1
doine On BEST ANSWER
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']
1
Michael Hodel On
names = ["Mary","John","Emma"]
heights = [180,165,170]
print(sorted(names, key=lambda n: -heights[names.index(n)]))

prints

['Mary', 'Emma', 'John']
1
Frank Yellin On
[name for _, name in sorted(zip(heights, names), reverse=True)]
0
Alain T. On

You could use a bit of zip/unpack trickery:

_,names[::-1] = zip(*sorted(zip(heights,names)))

print(names)
['Mary', 'Emma', 'John']