Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
custom count() for sorted() with key solution in Clear category for Sort Array by Element Frequency by ezebw2
def frequency_sort(items):
"""
Sorts (items) by frequency - sub-sorts ties by lower index.
"""
uniquesReference = set(items)
def counter(item):
"""
custom count() method defined as a function, to be later passed as key function for sorted()
ensures that same frequency elements are sub-sorted by index
"""
itemCount = list(items).count(item)
for reference in uniquesReference: #condition for tie-breaking: increase count value for each item with same count value and higher index value
if reference != item and list(items).count(reference) == itemCount and items.index(reference) > items.index(item):
itemCount += 1
return itemCount
return sorted(items, key=counter, reverse=True)
Aug. 10, 2020