26
2
Write a snippet to calculate the mode (most common number) of a list of positive integers.
For example, the mode of
d = [4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]
is 1
, because it occurs the maximum of 5 times.
You may assume that the list is stored in a variable such as d
and has a unique mode.
e.g.: Python, 49
max(((i,d.count(i))for i in set(d)), key=lambda x:x[1])
This is code-golf, so the shortest solution in bytes wins.
perfect, think @globby needs to see future :) – garg10may – 2014-12-19T16:25:17.253
12The great thing about this one is that it's not even golfy, it's just Pythonic. The only thing that's been golfed is a space between
d,
andkey=
. – wchargin – 2014-12-19T17:28:16.8275@WChargin: Eh, Pythonic would be to avoid the quadratic runtime by using
defaultdict(int)
orCounter
. Something likeCounter(d).most_common()[0]
. – user2357112 supports Monica – 2014-12-21T03:01:05.577