-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnagramFinder.py
70 lines (50 loc) · 3.84 KB
/
AnagramFinder.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# ░██████╗░██╗░░░██╗░█████╗░███╗░░██╗████████╗██╗░░░██╗███╗░░░███╗ ░██████╗████████╗░█████╗░░█████╗░██╗░░██╗
# ██╔═══██╗██║░░░██║██╔══██╗████╗░██║╚══██╔══╝██║░░░██║████╗░████║ ██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██║░██╔╝
# ██║██╗██║██║░░░██║███████║██╔██╗██║░░░██║░░░██║░░░██║██╔████╔██║ ╚█████╗░░░░██║░░░███████║██║░░╚═╝█████═╝░
# ╚██████╔╝██║░░░██║██╔══██║██║╚████║░░░██║░░░██║░░░██║██║╚██╔╝██║ ░╚═══██╗░░░██║░░░██╔══██║██║░░██╗██╔═██╗░
# ░╚═██╔═╝░╚██████╔╝██║░░██║██║░╚███║░░░██║░░░╚██████╔╝██║░╚═╝░██║ ██████╔╝░░░██║░░░██║░░██║╚█████╔╝██║░╚██╗
# ░░░╚═╝░░░░╚═════╝░╚═╝░░╚═╝╚═╝░░╚══╝░░░╚═╝░░░░╚═════╝░╚═╝░░░░░╚═╝ ╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝░╚════╝░╚═╝░░╚═╝
from collections import Counter
import sys
import time
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# Извлечение настроек из файла конфигурации
dictpath = config.get('AnagramFinder', 'DictionaryPath')
minlength = config.get('AnagramFinder', 'MinLength')
# Use: python AnagramFinder.py [letters without space]
# Example: python3 AnagramFinder.py битдеа
with open(dictpath, 'r') as f:
dictionary = f.read()
dictionary = [x.lower() for x in dictionary.split('\n')]
def return_anagrams(letters: str) -> list:
global dictionary, minlength
assert isinstance(letters, str), 'Scrambled letters should only be of type string.'
letters = letters.lower()
letters_count = Counter(letters)
anagrams = set()
for word in dictionary:
# Check if all the unique letters in word are in the scrambled letters
if not set(word) - set(letters):
check_word = set()
# Check if the count of each letter is less than or equal
# to the count of that letter in scrambled letter input
for k, v in Counter(word).items():
if v <= letters_count[k]:
check_word.add(k)
# Check if check_words is exactly equal to the unique letters
# in the word of the dictionary and the length is greater than or equal to minlength
if check_word == set(word) and len(word) >= int(minlength):
anagrams.add(word)
# Check if the empty string is in the set before attempting to remove it
if '' in anagrams:
anagrams.remove('')
return sorted(list(anagrams), key=lambda x: len(x))
if __name__ == '__main__':
start = time.time()
test_anagrams = return_anagrams(sys.argv[1])
print(test_anagrams)
stop = time.time()
print(f"Number of anagrams: {len(test_anagrams)}")
print(f"Time Taken: {round(stop - start, 5)} seconds")