Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Used the collections library to give a big assist. solution in Clear category for Sort Array by Element Frequency by Shakiestnerd
from collections import Counter
def frequency_sort(items):
""" This was a little tricky. Needed to use result.extend to join the lists
together. The most_common() function really helped out a lot.
"""
result = []
eggs = Counter(items)
for item, count in eggs.most_common():
result.extend([item] * count)
print(result)
return result
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]
assert list(frequency_sort([4, 6, 2, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 2, 2, 2, 6, 6]
print("Coding complete? Click 'Check' to earn cool rewards!")
Sept. 5, 2019