[Tutor] Cheating?No, not me:-)
Israel Evans
israel@lith.com
Wed, 17 Apr 2002 12:59:51 -0700
I just ran across something like this that used list comprehensions to do
this...
As far as I can remember it went like this:
>>> occ = {"hello":3, "name":23, "bob":15, "jane":10}
# switch the keys for the values
>>> pairs = [(v, k) for (k, v) in occ.items()]
>>> pairs
[(10, 'jane'), (15, 'bob'), (3, 'hello'), (23, 'name')]
>>> pairs.sort()
# reverse list so that most occurrences are at the front.
>>> pairs.reverse()
# switch back the keys and values.
>>> pairs = [(k, v) for (v, k) in pairs]
>>> pairs
[('name', 23), ('bob', 15), ('jane', 10), ('hello', 3)]
~Israel~
-----Original Message-----
From: Sean 'Shaleh' Perry [mailto:shalehperry@attbi.com]
Sent: 17 April 2002 12:43 PM
To: Nicole Seitz
Cc: tutor@python.org
Subject: Re: [Tutor] Cheating?No, not me:-)
>
> Thanks!
> My program now runs almost perfectly. And I solved the problem how to
print
> the K most common words. Maybe there's an easier way to determine the most
> common words, I don't know.
> Here's the little function that deals with the most common words.What do
you
> think of it?
>
> Note: occ is the dictionary where I store the words and their
occurences,e.g.
> occ = { "hello":3,"you":123,"fool":23}
try this:
$ python
>>> def value_sort(a,b):
... if a[1] == b[1]: return 0
... elif a[1] < b[1]: return -1
... else: return 1
...
>>> occ = {"hello":3, "name":23, "bob":15, "jane":10}
>>> values = zip(occ.keys(), occ.values())
>>> values
[('hello', 3), ('name', 23), ('bob', 15), ('jane', 10)]
>>> values.sort(value_sort)
>>> values
[('hello', 3), ('jane', 10), ('bob', 15), ('name', 23)]
Getting the first K items in that list should be easy enough.
zip() takes two lists and makes a list of tuples. the sort method of a list
takes an optional function which defines how to sort. This function returns
-1
when the first is less than the second, 0 when they are equal and 1 when the
first is greater than the second.
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor