Python/strings/anagrams.py

45 lines
1.1 KiB
Python
Raw Normal View History

from __future__ import annotations
import collections
import pprint
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
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
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)
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
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = \n ")
file.write(pprint.pformat(all_anagrams))