Skip to content

Instantly share code, notes, and snippets.

@danlmarmot
Last active August 29, 2015 14:05
Show Gist options
  • Save danlmarmot/f1c6e875041797a25df4 to your computer and use it in GitHub Desktop.
Save danlmarmot/f1c6e875041797a25df4 to your computer and use it in GitHub Desktop.
Anagram maker
__author__ = 'danlmarmot'
from itertools import permutations
import collections
INPUT_WORD = "deposit"
MIN_ANAGRAM_LEN = 4
WORD_DICT_FILEPATH = '/usr/share/dict/words'
def main():
words_as_dict = make_word_dict(WORD_DICT_FILEPATH)
look_for_anagrams(INPUT_WORD, words_as_dict, min_length=MIN_ANAGRAM_LEN)
def make_word_dict(word_filepath):
word_dict = collections.defaultdict(lambda: 0)
for w in open(word_filepath):
#strip off the /n character with w.strip()
word_dict[w.lower().strip()] += 1
return word_dict
def look_for_anagrams(input_word, word_dict, min_length=4):
anagram_count = 0
report_header = "Anagrams for " + input_word + ":"
print report_header
r = open("results.txt", "w")
r.write(report_header + "\n")
for i in range(min_length, len(input_word) + 1):
# reset this for each string length
answers_for_strlen = ([])
for item in permutations(input_word, i):
test_word = ''.join(item)
if test_word in word_dict.keys():
if test_word not in answers_for_strlen and test_word != input_word:
anagram_count += 1
print test_word
answers_for_strlen.append(test_word)
r.write(test_word + "\n")
report_summary = "Total number of anagrams found for '" + input_word + "': " + str(anagram_count)
print report_summary
r.write(report_summary + "\n")
r.close()
if __name__ == '__main__':
main()
@danlmarmot
Copy link
Author

This makes anagrams based on a provided word. Anagrams have to be at least 4 characters in length.

Tested against Python 2.7.6 on MacOS X, with the word dictionary at /usr/share/dict/words and the initial word of "deposit"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment