Skip to content

Instantly share code, notes, and snippets.

@julianbonilla
Last active November 10, 2017 15:42
Show Gist options
  • Save julianbonilla/cc220496579714620b1b69aff19f03be to your computer and use it in GitHub Desktop.
Save julianbonilla/cc220496579714620b1b69aff19f03be to your computer and use it in GitHub Desktop.
from itertools import permutations
# Generate a list of words to test for anagrams
perms = ['William Shakespeare', 'I am a weakish speller']
words = ['abc', 'def', 'gih']
for word in words:
perms.extend([''.join(p) for p in permutations(word)])
def compute_score(word):
"""Given a string, compute a score from the characters"""
score = 0
for char in word:
score = score + ord(char)
return score
def find_anagrams(words):
"""Given a list of words, return a grouping of the anagrams"""
scores = {}
for word in words:
score = compute_score(word.replace(' ', '').lower())
if score in scores:
scores[score].append(word)
else:
scores[score] = [word]
return scores
find_anagrams(perms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment