Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Plain one solution in Clear category for Sort Array by Element Frequency by Magu
def frequency_sort(items):
d = {}
l = []
for item in items:
d[item]=items.count(item)
d_sorted = sorted(d.items(), key = lambda x: x[1], reverse=True)
for tup in d_sorted:
for i in range(0, tup[1]):
l.append(tup[0])
return l
if __name__ == '__main__':
print("Example:")
print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))
assert list(frequency_sort([4,6,2,2,2,6,4,4,4])) == [4,4,4,4,2,2,2,6,6]
# 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!")
Aug. 31, 2021