anagram finder / dict mapping question
Kam-Hung Soh
kamhung.soh at gmail.com
Sat May 10 22:09:38 EDT 2008
On Sat, 10 May 2008 18:06:17 +1000, Arnaud Delobelle
<arnodel at googlemail.com> wrote:
> "Kam-Hung Soh" <kamhung.soh at gmail.com> writes:
>
>> On Sat, 10 May 2008 07:19:38 +1000, <umpsumps at gmail.com> wrote:
>>
>>>> > What would be the best method to print the top results, the one's
>>>> that
>>>> > had the highest amount of anagrams?? Create a new histogram dict?
>>>>
>>>> You can use the max() function to find the biggest list of anagrams:
>>>>
>>>> top_results = max(anagrams.itervalues(), key=len)
>>>>
>>>> --
>>>> Arnaud
>>>
>>> That is the biggest list of anagrams, what if I wanted the 3 biggest
>>> lists? Is there a way to specific top three w/ a max command??
>>>
>>
>> Built-in max() function only returns one result.
>>
>> My solution is to make a sorted list and return last three items:
>>
>> sorted((len(anagrams[key]), key) for key in anagrams.keys())[-3:]
>
> Using the key= parameter of sorted() beats explicit DSU:
>
> sorted(anagrams.itervalues(), key=len)[-3:]
>
> Or even
>
> sorted(anagrams.itervalues(), key=len, reverse=True)[:3]
>
Nice!
I just found out that DSU = Decorate-Sort-Undecorate idiom, from
http://wiki.python.org/moin/HowTo/Sorting.
--
Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>
More information about the Python-list
mailing list