Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Concise algorithm solution in Speedy category for Sort Array by Element Frequency by Igor_Sekretarev
def frequency_sort(items):
count = {}
unique_items = []
for item in items:
if item in count:
count[item] += 1
else:
count[item] = 1
unique_items.append(item)
items = []
for item in sorted(unique_items, key=lambda x: -count[x]):
items.extend([item] * count[item])
return items
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!")
April 24, 2021