[Tutor] anagrams

Karl Pflästerer sigurd at 12move.de
Wed Nov 5 18:08:59 EST 2003


On  5 Nov 2003, Karl Pflästerer <- sigurd at 12move.de wrote:

> Don't know if mine one is better; on my PC it's 30% faster than your
> solution.

Here is another solution.  It uses iterators instead of building a list.
With the small number  of anagram groups it's a bit slower but it would be
interesting to see it with really a lot og groups.


from itertools import *

f = open("wordlist.txt")

d = {}
for word in f:
    k, v = list(word.lower()), word
    k.sort()
    k = ''.join(k)
    if k in d:
        d[k].append(v)
    else:
        d[k] = [v]

f.close()


ang = izip(ifilter(lambda tup: tup[0] > 1,
                   imap(lambda i: (len(i), i), d.itervalues())),
           count(1))

s = 0
for k, v in ang:
    s += k[0]
print v, s



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list