Python/strings/anagrams.py

36 lines
868 B
Python
Raw Normal View History

import collections
import os
import pprint
import time
2016-09-06 12:34:53 +00:00
start_time = time.time()
2019-10-05 05:14:13 +00:00
print("creating word list...")
2016-09-06 12:34:53 +00:00
path = os.path.split(os.path.realpath(__file__))
with open(path[0] + "/words.txt") as f:
word_list = sorted(list({word.strip().lower() for word in f}))
2016-09-06 12:34:53 +00:00
2019-10-05 05:14:13 +00:00
2016-09-06 12:34:53 +00:00
def signature(word):
2019-10-05 05:14:13 +00:00
return "".join(sorted(word))
2016-09-06 12:34:53 +00:00
word_bysig = collections.defaultdict(list)
for word in word_list:
word_bysig[signature(word)].append(word)
2019-10-05 05:14:13 +00:00
def anagram(my_word):
return word_bysig[signature(my_word)]
2016-09-06 12:34:53 +00:00
2019-10-05 05:14:13 +00:00
print("finding anagrams...")
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}
print("writing anagrams to file...")
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = ")
2016-09-06 12:34:53 +00:00
file.write(pprint.pformat(all_anagrams))
total_time = round(time.time() - start_time, 2)
2019-10-05 05:14:13 +00:00
print(("Done [", total_time, "seconds ]"))