# Mean, median, and mode

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Dec 6 18:53:40 CET 2004

```This median expression is incorrect.  median is *not* the midpoint between
max and min values.  It is the middle value when all values are sorted (for
an odd number of values), or the average of the two middle values when all
values are sorted (for an even number of values).

In Python 2.4 (needed to use sorted() built-in), this can be one-lined as:
median = lambda x: ((x % 2) and (sorted(x)[len(x)>>1]) or
(sum(sorted(x)[(len(x)>>1):(len(x)>>1)+1])/2))

(not yet tested, as I've not installed v2.4 yet)
With boolean short-circuiting, this should only sort the list once.

-- Paul

"Sean McIlroy" <sean_mcilroy at yahoo.com> wrote in message
> >>> mean = lambda x: sum(x)/len(x)
> >>> median = lambda x: (max(x)-min(x))/2
> >>> mode = lambda x: max([(x.count(y),y) for y in x])
>
> "Robert Brewer" <fumanchu at amor.org> wrote in message
news:<mailman.7174.1102235108.5135.python-list at python.org>...
> > (now that we have a meaningful subject line)
> >
> > Alfred Canoy wrote:
> > > >>  I'm just new to programming and would like to ask for help..
> > > >>
> > > >> Build a module that contains three functions that do the following:
> > > >>
> > > >>       a.. Compute the average of a list of numbers
> > > >>       b.. Finds the statistical median value of a list of numbers
> > > >>       c.. Finds the mode of a list of numbers
> > > >>
> > > >> Can you please give me clue how I should start solving the
> > > >> following problem
> > > >> below? Here's the source code that I did so far:
> > > >>
> > > >> # compute the average of a list of numbers:
> > > >> # Keeps asking for numbers until 0 is entered
> > > >> # Prints the average value
> > > >>
> > > >> count = 0
> > > >> sum = 0
> > > >> number = 1
> > > >>
> > > >> print 'Enter 0 to exit the loop'
> > > >> while number != 0:
> > > >>     number = input ('Enter a number: ')
> > > >>     count = count + 1
> > > >>     sum = sum + number
> > > >> count = count -1
> > > >> print ' The average is:', sum/count
> >
> > For the mode, you might build a dictionary:
> >
> > freq = {}
> > while number != 0:
> >     number = input ('Enter a number: ')
> >     count = count + 1
> >     sum = sum + number
> >     try:
> >         freq[number] += 1
> >     except KeyError:
> >         freq[number] = 1
> >
> > ...then you can check for the largest value in that dictionary:
> >
> > max = 0
> > mode = None
> > for k, v in freq.iteritems():
> >     if v > max:
> >         max = v
> >         mode = k
> >
> > I leave the rest in your capable hands... ;) Including the case where
> > two numbers occur in equal frequencies. ;;)
> >
> >
> > Robert Brewer
> > MIS
> > Amor Ministries
> > fumanchu at amor.org

```