|
| 1 | +from __future__ import annotations |
| 2 | + |
1 | 3 | import collections |
2 | | -import os |
3 | 4 | import pprint |
4 | | -import time |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | + |
| 8 | +def signature(word: str) -> str: |
| 9 | + """Return a word sorted |
| 10 | + >>> signature("test") |
| 11 | + 'estt' |
| 12 | + >>> signature("this is a test") |
| 13 | + ' aehiisssttt' |
| 14 | + >>> signature("finaltest") |
| 15 | + 'aefilnstt' |
| 16 | + """ |
| 17 | + return "".join(sorted(word)) |
5 | 18 |
|
6 | | -start_time = time.time() |
7 | | -print("creating word list...") |
8 | | -path = os.path.split(os.path.realpath(__file__)) |
9 | | -with open(path[0] + "/words.txt") as f: |
10 | | - word_list = sorted(list({word.strip().lower() for word in f})) |
11 | 19 |
|
| 20 | +def anagram(my_word: str) -> list[str]: |
| 21 | + """Return every anagram of the given word |
| 22 | + >>> anagram('test') |
| 23 | + ['sett', 'stet', 'test'] |
| 24 | + >>> anagram('this is a test') |
| 25 | + [] |
| 26 | + >>> anagram('final') |
| 27 | + ['final'] |
| 28 | + """ |
| 29 | + return word_bysig[signature(my_word)] |
12 | 30 |
|
13 | | -def signature(word): |
14 | | - return "".join(sorted(word)) |
15 | 31 |
|
| 32 | +data: str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8") |
| 33 | +word_list = sorted({word.strip().lower() for word in data.splitlines()}) |
16 | 34 |
|
17 | 35 | word_bysig = collections.defaultdict(list) |
18 | 36 | for word in word_list: |
19 | 37 | word_bysig[signature(word)].append(word) |
20 | 38 |
|
| 39 | +if __name__ == "__main__": |
| 40 | + all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} |
21 | 41 |
|
22 | | -def anagram(my_word): |
23 | | - return word_bysig[signature(my_word)] |
24 | | - |
25 | | - |
26 | | -print("finding anagrams...") |
27 | | -all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} |
28 | | - |
29 | | -print("writing anagrams to file...") |
30 | | -with open("anagrams.txt", "w") as file: |
31 | | - file.write("all_anagrams = ") |
32 | | - file.write(pprint.pformat(all_anagrams)) |
33 | | - |
34 | | -total_time = round(time.time() - start_time, 2) |
35 | | -print(("Done [", total_time, "seconds ]")) |
| 42 | + with open("anagrams.txt", "w") as file: |
| 43 | + file.write("all_anagrams = \n ") |
| 44 | + file.write(pprint.pformat(all_anagrams)) |
0 commit comments