[Tutor] get the mode of a list

Nick Lunt nick at javacat.f2s.com
Thu Oct 21 21:12:30 CEST 2004


Hi folks,

I really have been putting off posting this to the list cos Im sure there's
an easy way to do it, but I give up... :(

I want to return the mode of a list, just to clarify the mode is the most
frequently occurring member of a list in my case.

Here's a function that 90% works:

[code]
>>> def mode(alist):
# this only works for a single most freq item, ie [1,2,3333] but not
[1,2,2,3,3]
	start = 1
	current = 0
	new = 0
	for i in alist:
		if alist.count(i) > start:
			current = alist.count(i)
			start = current
			new = i
	if new > 1:
		return new
	else:
		return "All members of [%s] are modes." %alist


>>> mode([10,20,30])
'All members of [[10, 20, 30]] are modes.'
>>> mode([9,9,9,8])
9
>>> mode([10,10,20,20,5,6,7]) # *****
10
[/code]

As you can see it doesn't do a good job of recognising a list which is
multimodal.
The line near the end of the code section above (*****) is a multimodal
list, I want the mode function to return [10,20] in these cases.

So after all that waffling, what I want to do is return the modes of a
mulitmodal list.

I'd appreciate some help here, before I pull whats left of my hair out :)

Cheers
Nick.

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.778 / Virus Database: 525 - Release Date: 15/10/2004



More information about the Tutor mailing list