[Tutor] get the mode of a list

Nick Lunt nick at javacat.f2s.com
Fri Oct 22 18:36:55 CEST 2004


Hi Danny, Jacob and Terry,

thankyou for your help.

Danny: I had looked at using a dictionary for this, as here:

>>> def mode(alist):
	modes = {}
	for i in alist:
		modes[i] = alist.count(i)
	return modes

so for example
>>> mode([10,10,10,20,10,30,45,346,45])
{10: 4, 346: 1, 20: 1, 45: 2, 30: 1}

The problem I had here was not getting the max value in the dictionary, but
getting the max when there was >1 max value :)
However, now that you have hinted that using a dictionary is a good way to
do it, I will do so, thankyou.

Jacob and Terry:

Many thanks for you solutions. I will look at them after I've come up with
my own solution ;)

Python is a learning curve for me, even tho I do use it fairly often in my
day job.

This project I'm working on is to eventually work out the standard deviation
to help out a friend, and getting the mode/median/mean working first seemed
a sensible thing to do...

Many thanks for all your help,
Nick.


-----Original Message-----
From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu]
Sent: 21 October 2004 20:39
To: Nick Lunt
Cc: Python Tutor
Subject: Re: [Tutor] get the mode of a list




On Thu, 21 Oct 2004, Nick Lunt wrote:

> 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.

Hi Nick,


Here's a more general problem that might be easier to solve: can you write
a function that generates a "histogram"?  That is, can you get the
frequencies of all the elements in a list?


For example, something like:

###
>>> histogram([10, 10, 20, 5, 6, 7])
{ 10 : 2,
  20 : 2,
  5 : 1,
  6 : 1,
  7 : 1}
###

If you have something that can generate histogram dictionaries, then you
can use it to solve for modes with relative ease, I think.


Good luck!

---
Incoming 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

---
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