Sort the distinct elements of a list in descending order by frequency
APL (14)
{∪⍵[⍒+⌿∘.≡⍨⍵]}
This is a function that takes a list, e.g.:
names
John Doe Dick Harry Harry Doe Doe Harry Doe John
{∪⍵[⍒+⌿∘.≡⍨⍵]} names
Doe Harry John Dick
Explanation:
∘.≡⍨⍵
: compare each element in the array to each other element in the array, giving a matrix+⌿
: sum the columns of the matrix, giving how many times each element occurs⍒
: give indices of downward sort⍵[
...]
: reorder⍵
by the given indices∪
: get the unique elements
Python 3 - 47 43; Python 2 - 40 39
For Python 3:
f=lambda n:sorted(set(n),key=n.count)[::-1]
For Python 2:
f=lambda n:sorted(set(n),cmp,n.count,1)
Demo:
>>> names = ["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"]
>>> f(names)
['Doe', 'Harry', 'John', 'Dick']
Mathematica, 31
Sort[GatherBy@n][[-1;;1;;-1,1]]
{"Doe", "Harry", "John", "Dick"}
(With n = {"John", "Doe", "Dick", "Harry", "Harry", "Doe", "Doe", "Harry", "Doe", "John"}
)