Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Sort Array by Element Frequency by donnythelegend
def frequency_sort(items):
# Initialize new empty list.
items_new = []
# Loop through items.
for i in items:
# Check if i is not in items.
if i not in items_new:
# Nested loop through items.
for j in items:
# Append j to items_new if it is the same as i.
# This groups elements together to be sorted.
if j==i:
items_new.append(j)
# Return items_new sorted by frequency in descending order.
return sorted(items_new, key=items_new.count, reverse=True)
# Delete items since it's not needed in this case.
del(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 19, 2021
Comments: