Re: Modal value of an array
- From: bearophileHUGS@xxxxxxxxx
- Date: 29 Mar 2007 06:03:32 -0700
Alex Martelli:
foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
max(foo, key=foo.count)
It's a very nice solution, the shortest too. But I think it's better
to develop your own well tested and efficient stats module (and there
is one already done that can be found around) and import it when you
need functions, instead of using similar onliners or re-writing code.
As you know your solution becomes rather slow if the list is quite
long, and it works with lists only.
This uses more memory but it's probably much faster for longer
interables:
from collections import defaultdict
def mode(seq):
freqs = defaultdict(int)
for el in seq:
freqs[el] += 1
return max(freqs.itervalues())
Generally you may want to know what's the mode element(s) too:
def mode2(seq):
freqs = defaultdict(int)
for el in seq:
freqs[el] += 1
maxfreq = max(freqs.itervalues())
mode_els = [el for el,f in freqs.iteritems() if f == maxfreq]
return maxfreq, mode_els
foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
print mode(foo)
print mode2(foo)
Bye,
bearophile
.
- References:
- Modal value of an array
- From: datta.abhirup@xxxxxxxxx
- Re: Modal value of an array
- From: Ben Finney
- Re: Modal value of an array
- From: Alex Martelli
- Modal value of an array
- Prev by Date: Re: Finding User Profile path
- Next by Date: Weird gcc behaviour with function pointer types
- Previous by thread: Re: Modal value of an array
- Next by thread: Re: Modal value of an array
- Index(es):
Relevant Pages
|
|