anagram finder / dict mapping question

Kam-Hung Soh kamhung.soh at gmail.com
Thu May 8 22:09:14 EDT 2008


On Fri, 09 May 2008 09:52:53 +1000, dave <squareswallower at 1ya2hoo3.net>  
wrote:

> I got it!  Thanks for all your help!!!  Please tell me what you think:
>
> def anafind():
>             fin = open('short.txt')			#one word per line
>             mapdic = {}					#this dic maps letters to anagrams
>             for line in fin:
>                         line = line.strip()
>                         templist = sorted(list(line))	#sort letters
>                         newtlist = (''.join(templist)) 	#join letters
>                         if newtlist not in mapdic:
>                                     mapdic[newtlist] = [line]
>                         if line not in mapdic[newtlist]:
>                                     mapdic[newtlist].append(line)
>             for value in mapdic.values():
>                         if len(value) <= 1:
>                                     pass
>                         else:
>                                     print value
>
>

I avoid creating a temporary variable if it's only used once immediately,  
so I would have written:

newtlist = ''.join(sorted(list(line)))

Looks pretty good, and I found the other tips in parallel responses useful  
to me too!

-- 
Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>



More information about the Python-list mailing list