Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Frequency Sorting by Mohamed-Hossam
from typing import List
def frequency_sorting(numbers: List[int]) -> List[int]:
freq = {number: numbers.count(number) for number in numbers}
# The following dictionary sorts numbers by the highset freequency. The negative sign in -x[1] means to sort
# in the descending or the highest value of the frequency value. x[0] is a secondary key that sorts
# in the ascending order of the number value if the frequency value of two or more numbers are the same.
freq_sorted = dict(sorted(freq.items(), key=lambda x: (-x[1], x[0])))
result = [number for number, freq in freq_sorted.items() for _ in range(freq)]
return result
if __name__ == "__main__":
print("Example:")
print(frequency_sorting([1, 2, 3, 4, 5]))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert frequency_sorting([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5], "Already sorted"
assert frequency_sorting([3, 4, 11, 13, 11, 4, 4, 7, 3]) == [
4,
4,
4,
3,
3,
11,
11,
7,
13,
], "Not sorted"
assert frequency_sorting([99, 99, 55, 55, 21, 21, 10, 10]) == [
10,
10,
21,
21,
55,
55,
99,
99,
], "Reversed"
print("Coding complete? Click 'Check' to earn cool rewards!")
May 22, 2022
Comments: