quick question

John Hunter jdhunter at nitace.bsd.uchicago.edu
Sat Nov 16 09:52:42 EST 2002


>>>>> "Bwfc10" == Bwfc10  <bwfc10 at aol.com> writes:

    Bwfc10> If you were writing a program aking about peoples
    Bwfc10> favourite flavour of ice cream and you input the number of
    Bwfc10> votes for 5 flavours, how do you get your program to
    Bwfc10> display the most popular (the one with the most votes).
    Bwfc10> This may be easy to most of you but i am new to python.

This isn't homework, is it :-)? 

Python has a number of data structures to make your life easier.
Let's start with the end result, and then I'll show you how to get
there.  Suppose you had a list of tuples, each tuple was a pair of
vote tallies and icecreams

votes = [ (12, 'vanilla'),
          (53, 'chocolate'),
          (1003, 'rocky road'),
          (1, 'rasberry sorbet'),
          ]

python lists have an in place sort method, which for lists of tuples
will sort on the first element of the tuple, which is what we want
since vote counts are the first element of each tuple,  If you want to
display the winners first,  you can reverse the list

votes.sort()
votes.reverse()  # winners first!

for (count, flavor) in votes:
    print '%s got %d votes' % (flavor, count)

Now, all that remains to be done is generate the list in the first
place.  This depends on how you collect your data, but a good
structure to use is a dictionary that maps flavors to counts.  Suppose
you had a long text file, where every row was the favorite flavor of
somebody, eg

chocolate
vanilla
chocolate
rocky road
vanilla
rasberry sorbet

... and so on...

You can loop over that file and create a dictionary mapping flavors to
counts like so:

favorites = {}  
for flavor in file('votes.dat'):
    flavor = flavor.strip()  # remove leading or trailing white space
    favorites[flavor] = favorites.get(flavor,0) + 1


This last line is a common idiom for dictionaries.  get returns the
value of flavor if it exists, otherwise it returns the default value
of 0.

favorites looks like

{'rocky road': 1, 'rasberry sorbet': 1, 'vanilla': 2, 'chocolate': 2}

Now were almost done.  We just need to get that dictionary into the
list of tuples used above.

votes = [(count, flavor) for (flavor, count) in m.items()]


Here then, is the complete program:

favorites = {}  
for flavor in file('votes.dat'):
    flavor = flavor.strip()  # remove leading or trailing white space
    favorites[flavor] = favorites.get(flavor,0) + 1

votes = [(count, flavor) for (flavor, count) in favorites.items()]
votes.sort()
votes.reverse()  # winners first!

for (count, flavor) in votes:
    print '%s got %d votes' % (flavor, count)

There is a chapter on sorting in The Python Cookbook that you should
read if you get your hands on it.

John Hunter




More information about the Python-list mailing list