Skip to content

Instantly share code, notes, and snippets.

@JayH5
Last active April 5, 2018 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JayH5/6050bb67b57b3f11255b2482e6ca2e56 to your computer and use it in GitHub Desktop.
Save JayH5/6050bb67b57b3f11255b2482e6ca2e56 to your computer and use it in GitHub Desktop.
Python example: Anagram counter
from collections import defaultdict
def anagram_counter(words, n):
lookup = defaultdict(set)
for word in words:
if len(word) == n:
lookup[lookup_key(word)].add(word)
num_anagrams = 0
for anagram_words in lookup.values():
# An anagram must have at least two words with the same letters
if len(anagram_words) > 1:
num_anagrams += 1
return num_anagrams
def lookup_key(word):
# Return the sorted, lower-case letters of the word
return "".join(sorted(word.lower()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment