[Tutor] mode??
Kent Johnson
kent_johnson at skillsoft.com
Tue Jul 27 02:42:19 CEST 2004
Here is one way to do it. This will find the mode(s) of a list of any kind
of items, not just numbers.
Kent
def mode(items):
"Find the mode(s) of a list of items"
# If items is empty then there is no mode
if not items:
return None
# Create a dictionary that maps each item to the number of times it occurs
# (i.e. a histogram)
hist = {}
for item in items:
count = hist.get(item, 0)
hist[item] = count + 1
# Get the results to a list and sort by number of occurrances
result = [ (count, item) for item, count in hist.items() ]
result.sort()
result.reverse()
# The first entry has the number of times the mode occurs
maxcount = result[0][0]
# Find all the items that occur maxcount times
modes = [ item for count, item in result if count == maxcount ]
return modes
print mode([1,2,2,5,3,4,6,5])
print mode([])
print mode(['a', 2, 'b', 2, 'a', 'a'])
prints
[5, 2]
None
['a']
At 07:52 PM 7/26/2004 -0400, jason hochstein wrote:
>I am having trouble understanding how you would get a program to output
>the mode of a group of numbers. I got it to do the mean and median but if
>there are 7 n umbers and all are different how would you get a mode.
>Further more if there a re 7 numbers and 2 or 3 are the same, I understand
>thats the mode but how do you get it to output?
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list