-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalingrams.py
More file actions
55 lines (42 loc) · 1.6 KB
/
palingrams.py
File metadata and controls
55 lines (42 loc) · 1.6 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
45
46
47
48
49
50
51
52
53
54
55
"""Finds word pairs that form palindromes from a dictionary file."""
import cProfile
import time
def load_file(file_name: str) -> list:
"""
Load a text file and return a list of lowercase, stripped strings.
Args:
file_name (str): The path to the dictionary file.
Returns:
list: A list of words from the file.
"""
with open(file_name, "r", encoding="utf-8") as file:
content = file.read().split("\n")
content = [x.lower().strip() for x in content]
return content
def find_palingrams(dict_path: str) -> list:
"""
Find all palingram pairs in a given dictionary file.
Args:
dict_path (str): The path to the dictionary file.
Returns:
list: A list of tuples containing the palingram pairs.
"""
content = set(load_file(dict_path))
palindromes = set()
for w in content:
for i in range(len(w)):
prefix = w[:i]
suffix = w[i:]
if prefix == prefix[::-1] and suffix[::-1] in content and suffix[::-1] != w:
palindromes.add((suffix[::-1], w))
if suffix == suffix[::-1] and prefix[::-1] in content and prefix[::-1] != w:
palindromes.add((w, prefix[::-1]))
return palindromes
if __name__ == "__main__":
start_time = time.time()
palingrams = find_palingrams("dict.txt")
end_time = time.time()
print(f"\nRuntime for this program was {end_time - start_time:.4f} seconds.\n")
sorted_palingrams = sorted(palingrams)
print(f"Found {len(sorted_palingrams)} palingrams.")
cProfile.run('find_palingrams("dict.txt")')