2021-11-08 17:58:15 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2020-05-22 06:10:11 +00:00
|
|
|
import collections
|
|
|
|
import pprint
|
2021-11-08 17:58:15 +00:00
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
|
|
def signature(word: str) -> str:
|
|
|
|
"""Return a word sorted
|
|
|
|
>>> signature("test")
|
|
|
|
'estt'
|
|
|
|
>>> signature("this is a test")
|
|
|
|
' aehiisssttt'
|
|
|
|
>>> signature("finaltest")
|
|
|
|
'aefilnstt'
|
|
|
|
"""
|
|
|
|
return "".join(sorted(word))
|
2016-09-06 12:34:53 +00:00
|
|
|
|
|
|
|
|
2021-11-08 17:58:15 +00:00
|
|
|
def anagram(my_word: str) -> list[str]:
|
|
|
|
"""Return every anagram of the given word
|
|
|
|
>>> anagram('test')
|
|
|
|
['sett', 'stet', 'test']
|
|
|
|
>>> anagram('this is a test')
|
|
|
|
[]
|
|
|
|
>>> anagram('final')
|
|
|
|
['final']
|
|
|
|
"""
|
|
|
|
return word_bysig[signature(my_word)]
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2021-11-08 17:58:15 +00:00
|
|
|
data: str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8")
|
|
|
|
word_list = sorted({word.strip().lower() for word in data.splitlines()})
|
2016-09-06 12:34:53 +00:00
|
|
|
|
|
|
|
word_bysig = collections.defaultdict(list)
|
|
|
|
for word in word_list:
|
|
|
|
word_bysig[signature(word)].append(word)
|
|
|
|
|
2021-11-08 17:58:15 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2021-11-08 17:58:15 +00:00
|
|
|
with open("anagrams.txt", "w") as file:
|
|
|
|
file.write("all_anagrams = \n ")
|
|
|
|
file.write(pprint.pformat(all_anagrams))
|