Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
stevenxu77 solution in Clear category for Sort Array by Element Frequency by stevenxu77
def frequency_sort(items):
# your code here
if len(items) < 2:
return items
count_dict = {}
for i in items:
if not (i in count_dict.keys()):
count_dict[i] = items.count(i)
sorted_dict = dict(sorted(count_dict.items(),key=lambda item:item[1],reverse=True))
return_list = []
for i in sorted_dict.keys():
for y in range (0, sorted_dict[i]):
return_list.append(i)
return return_list
if __name__ == '__main__':
print("Example:")
print(frequency_sort([4, 6, 2, 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 1, 2021
Comments: