Posted by Kevin D Smith @ 3:26 am on March 22nd 2007

CodeKata #6

I’ve been working through Dave Thomas’ CodeKata for the past few weeks. I get to about one or two a week. I just finished number six which has been the most fun so far. Dave’s told about his solution in Ruby that was 25 lines and took 1.5s on his 1GHz machine. Since I’m more of a Python fan than a Ruby fan, I thought I’d take a shot at his numbers. Here is my 7 line solution.

words = {}
for word in open('wordlist.txt'):
    key = ''.join(sorted(list(word.strip().lower())))
    words.setdefault(key, []).append(word.strip())
for v in sorted(words.values()):
    if len(v) > 1:
        print ' '.join(v)

This could be shortened to 5 lines, but isn’t quite as readable.

words = {}
for word in open('wordlist.txt'):
    words.setdefault(''.join(sorted(list(word.strip().lower()))), []).append(word.strip())
for v in [x for x in sorted(words.values()) if len(x) > 1]:
    print ' '.join(v)

On my 1.83GHz MacBook, this took 0.56s.