forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagrams.py
More file actions
Latest commit
44 lines (34 loc) · 1.13 KB
/
Copy pathanagrams.py
File metadata and controls
44 lines (34 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from __future__ importannotations
importcollections
importpprint
frompathlibimportPath
defsignature(word: str) ->str:
"""Return a word sorted
>>> signature("test")
'estt'
>>> signature("this is a test")
' aehiisssttt'
>>> signature("finaltest")
'aefilnstt'
"""
return"".join(sorted(word))
defanagram(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']
"""
returnword_by_signature[signature(my_word)]
data: str=Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8")
word_list=sorted({word.strip().lower() forwordindata.splitlines()})
word_by_signature=collections.defaultdict(list)
forwordinword_list:
word_by_signature[signature(word)].append(word)
if__name__=="__main__":
all_anagrams= {word: anagram(word) forwordinword_listiflen(anagram(word)) >1}
withopen("anagrams.txt", "w") asfile:
file.write("all_anagrams = \n ")
file.write(pprint.pformat(all_anagrams))