Files
Python/strings/anagrams.py

52 lines
1.3 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's frequency-based signature.
>>> signature("test")
'e1s1t2'
>>> signature("this is a test")
' 3a1e1h1i2s3t3'
>>> signature("finaltest")
'a1e1f1i1l1n1s1t2'
"""
frequencies = collections.Counter(word)
return "".join(
f"{char}{frequency}" for char, frequency in sorted(frequencies.items())
)
2016-09-06 18:04:53 +05:30
def anagram(my_word: str) -> list[str]:
"""
Return every anagram of the given word from the dictionary.
>>> anagram('test')
['sett', 'stet', 'test']
>>> anagram('this is a test')
[]
>>> anagram('final')
['final']
"""
return word_by_signature[signature(my_word)]
2019-10-05 01:14:13 -04: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 18:04:53 +05:30
word_by_signature = collections.defaultdict(list)
2016-09-06 18:04:53 +05:30
for word in word_list:
word_by_signature[signature(word)].append(word)
2016-09-06 18:04:53 +05:30
if __name__ == "__main__":
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}
2019-10-05 01:14:13 -04:00
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = \n")
file.write(pprint.pformat(all_anagrams))