Skip to content

Instantly share code, notes, and snippets.

@wasi0013
Created July 31, 2016 16:18
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 wasi0013/24c5250d2435df8ab904b5d8e31a4895 to your computer and use it in GitHub Desktop.
Save wasi0013/24c5250d2435df8ab904b5d8e31a4895 to your computer and use it in GitHub Desktop.
A naive implementation of an Anagram Generator
__author__ = "wasi0013"
import glob
def get_dictionary(path):
"""
returns: a dictionary of words (with sorted string as key)
from files in the path
"""
words = set()
for filename in glob.glob(path):
#print(filename)
with open(filename,'r') as f:
for new_word in iter(f):
words.add(new_word.strip('\n').strip("'s").lower())
dictionary = dict()
for word in words:
key = "".join(sorted(word)).lower()
if key not in dictionary:
dictionary[key] = list()
dictionary[key].append(word)
return dictionary
def anagram(word, dictionary):
"""
returns: a list of all anagram(s) of the word or None
"""
key = "".join(sorted(word)).lower()
if key in dictionary:
return dictionary[key]
def main():
path = "/usr/share/dict/*-english" #contains list of english words in ubuntu
dictionary = get_dictionary(path)
print(anagram("silent", dictionary))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment