Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using sorting stability. solution in Clear category for Sort Array by Element Frequency by DahliaSR
"""
The built-in function "sorted" uses an stable sorting algorithm.
This guarantuees that the relative order of elements, that do compare equal is kept.
This allows to sort by multiple keys wich have different priorities.
Sort by the key with the lowest precedence first, and sort that result by the key with next higher precedence.
"""
def frequency_sort(items):
return sorted(
sorted(items, key=items.index), key=items.count, reverse=True
)
if __name__ == '__main__':
print("Example:")
print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))
# These "asserts" are used for self-checking and not for an auto-testing
#assert list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2]
#assert list(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == ['bob', 'bob', 'bob', 'carl', 'alex']
#assert list(frequency_sort([17, 99, 42])) == [17, 99, 42]
#assert list(frequency_sort([])) == []
#assert list(frequency_sort([1])) == [1]
#print("Coding complete? Click 'Check' to earn cool rewards!")
Dec. 30, 2021
Comments: