[Tutor] anagrams

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Nov 5 18:32:09 EST 2003



On Thu, 6 Nov 2003, Karl [iso-8859-1] Pfl=E4sterer wrote:

> On  5 Nov 2003, Karl Pfl=E4sterer <- sigurd at 12move.de wrote:
>
> > Don't know if mine one is better; on my PC it's 30% faster than your
> > solution.

Time to jump in as well!  *grin*

###
def main():
    for anagrams in find_anagrams(open("wordlist.txt").readlines()):
        if len(anagrams) > 1:
            print '\t'.join(anagrams)


def anagram_signature(word):
    """Finds the anagram "signature" of a word."""
    letters =3D list(word.lower().strip())
    letters.sort()
    return ''.join(letters)


def find_anagrams(words):
    """Returns a partitioning of words into equivalence classes, based on
    a word's anagram signature."""
    d =3D {}
    for word in words:
        d.setdefault(anagram_signature(word), []).append(word.strip())
    return d.values()


if __name__ =3D=3D '__main__':
    main()
###




More information about the Tutor mailing list