Sort Array by Element Frequency

Sort Array by Element Frequency

Sort the given list so that its elements should be grouped and those groups end up in the decreasing frequency order, that is, the number of times element appears in list. If two elements have the same frequency, their groups should end up in the same order as the first appearance of element in the list.

example

If you want to practice more with the similar case, try Frequency Sorting mission.

Input: List

Output: List or another Iterable (tuple, iterator, generator)

Examples:

assert list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2]
assert list(frequency_sort([4, 6, 2, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 2, 2, 2, 6, 6]
assert list(frequency_sort(["bob", "bob", "carl", "alex", "bob"])) == [
    "bob",
    "bob",
    "bob",
    "carl",
    "alex",
]
assert list(frequency_sort([17, 99, 42])) == [17, 99, 42]

How it is used: For analyzing data using mathematical statistics and mathematical analysis, and for finding trends and predicting future changes (systems, phenomena, etc.)

Precondition:

  • elements can be ints or strings

The mission was taken from Python CCPS 109 Fall 2018. It's being taught for Ryerson Chang School of Continuing Education by Ilkka Kokkarinen

40