Created
July 31, 2016 16:18
-
-
Save wasi0013/24c5250d2435df8ab904b5d8e31a4895 to your computer and use it in GitHub Desktop.
A naive implementation of an Anagram Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__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