Order by a score you compute
Sort numbers by a score that you work out for each one, and break ties with the number itself. About 10 minutes.
Sort by a key
Often the order you want isn't the numbers' own size. Here you must order whole numbers by how many 1s they have when written in binary, and when two numbers have the same count, the smaller number comes first.
Don't write a new sort. Give each number a key, here the pair of its 1-count and its value, and let the sort compare keys. The pair compares the first part first, and only looks at the second part when the first parts are equal.
nums.sort(key=lambda n: (n % 10, n)) # sorted by the last digit
Work out each score: 6 is 110 (two 1s), 9 is 1001 (two), 2 is 10 (one), 7 is 111 (three), 12 is 1100 (two).
Two numbers have the same number of 1s in binary. How are they ordered?
- ABy their own value, smaller first
- BBy the order they were given
- CIn any order
Show the answer
By their own value, smaller first. That is the second part of the key, used only when the first parts tie.
Order by the number of ones
nums is a list of non-negative whole numbers. Sort them by how many 1s each has when written in binary, fewest first. Numbers with the same count are sorted by their own value, smallest first. Return the sorted list.
nums = [5, 3, 7, 8, 1] → [1, 8, 3, 5, 7]
0 ≤ length ≤ 3,000 · 0 ≤ value ≤ 1,000,000,000