Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Sort Array by Element Frequency by H0r4c3
from itertools import repeat
def frequency_sort(items):
my_dict = dict()
my_list = list()
for item in items:
count = items.count(item)
my_dict[item] = count
sorted_list = sorted(my_dict.items(), key = lambda x : x[1], reverse=True)
sorted_dict = dict(sorted_list)
print(sorted_dict)
my_list = [x for item in sorted_dict for x in repeat(item, my_dict[item])]
return my_list
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!")
Nov. 11, 2021
Comments: