-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrut.py
118 lines (97 loc) · 2.64 KB
/
brut.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import sys
frequency = {'ъ': 4,
'р': 473,
'д': 298,
'ш': 73,
'й': 121,
'э': 32,
'ф': 26,
'е': 845,
'ь': 174,
'ы': 190,
'о': 1097,
'л': 440,
'и': 735,
'к': 349,
'п': 281,
'ю': 64,
'н': 670,
'ч': 144,
'ж': 94,
'я': 201,
'г': 170,
'т': 626,
'с': 547,
'б': 159,
'а': 801,
'м': 321,
'у': 262,
'х': 97,
'в': 454,
'з': 165,
'щ': 36,
'ё': 4,
'ц': 48}
alph = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
Alph = str([i.upper() for i in alph])
def char_shift(char, shift):
global alph, Alph
char_ord = alph.find(char)
if char_ord != -1:
char_ord = (char_ord + shift) % len(alph)
return alph[char_ord]
char_ord = Alph.find(char)
if char_ord == -1:
return char
char_ord = (char_ord + shift) % len(Alph)
return Alph[char_ord]
def text_shift(text, shift):
return ''.join([char_shift(i, shift) for i in text])
def make_counting(text):
global alph
chars_frequency = dict()
for i in alph:
chars_frequency[i] = 0
for i in text:
i = i.lower()
if i in chars_frequency:
chars_frequency[i] += 1
return chars_frequency
def shift_counting(counting, shift):
new_counting = dict()
for i in counting:
new_counting[char_shift(i, shift)] = counting[i]
return new_counting
def calc_differ(counting):
global frequency
x = 0
for i in counting:
x += frequency[i] * counting[i]
return x
def brut(text):
shifts = 33 * [0]
current_counting = make_counting(text)
for i in range(33):
shifts[i] = (calc_differ(shift_counting(current_counting, i)), i)
maxx = max(shifts)
return maxx[1]
def check_args():
file = None
n = len(sys.argv)
if n < 2:
sys.stderr.write('File name not found\n')
raise Exception("FileError")
encoding = 'utf8'
if n >= 3:
encoding = sys.argv[2]
if file is None:
file = open(sys.argv[1], encoding=encoding)
s = file.read()
file.close()
return s
return sys.stdin.read()
def main():
s = check_args()
shift = brut(s)
print(text_shift(s, shift))
main()