Intermediate · Sorting · 149 of 264
Nearest points
Sort points by their distance from (0, 0), nearest first. Points at the same distance go in the order they were given.
Input: n, then n lines "x y". Output: the points, one per line, as x y
Examples
Input
3 3 4 1 1 0 2
Output
1 1 0 2 3 4
Input
1 5 5
Output
5 5
One more test checks other inputs when you press Check.
Stuck? The idea behind sorting
sorted() gives a new sorted list; list.sort() sorts the list itself. reverse=True sorts from largest to smallest.
key= says what to sort by: key=len sorts words by length, key=lambda p: p[1] sorts pairs by their second item.
people = [("Ann", 14), ("Bob", 12)]
for name, age in sorted(people, key=lambda p: p[1]):
print(name, age)Watch for: list.sort() gives back None: names = names.sort() loses the list. Use sorted() for a new one.