For the Win

Today’s kata was in python.

The question was a classic computer science ask.  Identify an anagram.  As a reminder an anagram is simply rearranging the letters to form a new word.  The only rule, you can’t add or subtract a charcter.

My solution beat out 99.3% of the previous solutions in execution time.  The bell curve had a mean of 68 ms and my solution ran in 36 ms on aveage through the 34 tests.

import collections

s = “anagram”
t = “nagaram”

dict1 = collections.Counter(s)
dict2 = collections.Counter(t)

if dict1 == dict2:
    print(“We have an anagram.”)
Sometimes the simple solution is the best solution.  In this case I could have had nested loops to walk through each string and verify that it was indeed an anagram.  Not only does the solution work, it is elegant, and I like it!
No comments yet.

Leave a Reply