Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
bad method using pandas :) solution in 3rd party category for Sort Array by Element Frequency by lucas.stonedrake
import pandas as pd
def frequency_sort(items):
if len(items) <= 2: return items # return the simple cases
#create a dataframe from items and the frequencies of each item
df = pd.DataFrame(zip(items, [items.count(x) for x in items]))
#sort descending by frequencies
df.sort_values(by =1, ascending=False, inplace=True)
#group by frequeny but do not sort
df = df.groupby([0], sort=False)[1].count()
#create a list of each unique entry the number of times it occurs in items
return [x for x in df.index for i in range(items.count(x))]
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!")
Oct. 8, 2020
Comments: