-
Notifications
You must be signed in to change notification settings - Fork 183
/
03 - Basic Cryptanalysis.py
104 lines (79 loc) · 2 KB
/
03 - Basic Cryptanalysis.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
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/basic-cryptanalysis/problem
# Difficulty: Hard
# Max Score: 50
# Language: Python
# ========================
# Solution
# ========================
import re
f = open('dictionary.lst', 'r')
data = f.read().lower()
f.close()
words = data.split()
wordmap = {}
for word in words:
length = len(word)
sub = wordmap.get(length, {})
wordmap[length] = sub
gen = ''
for c in word:
if c not in gen:
gen += c
key = [0] * length
for i, c in enumerate(word):
key[i] = gen.index(c)
key = ' '.join([str(k) for k in key])
arr = sub.get(key, [])
sub[key] = arr
arr.append(word)
alpha = 'abcdefghijklmnopqrstuvwxyz'
cypher = ['.'] * 26
data = input()
enc = data.split()
test = enc[:]
def cycle():
global test, cypher, alpha, wordmap
for word in test:
length = len(word)
gen = ''
for c in word:
if c not in gen:
gen += c
key = [0] * length
pattern = ''
for i, c in enumerate(word):
key[i] = gen.index(c)
try:
j = cypher.index(c)
pattern += alpha[j]
except:
pattern += '.'
key = ' '.join([str(k) for k in key])
matches = wordmap[length][key]
copy = []
for match in matches:
if re.fullmatch(pattern, match):
copy.append(match)
matches = copy
if len(matches) == 1:
test.remove(word)
match = matches[0]
for i in range(length):
x = alpha.index(match[i])
cypher[x] = word[i]
i = len(test)
while True:
cycle()
j = len(test)
if i == j:
break
i = j
cypher = ''.join(cypher)
out = [' '] * len(data)
for i, c in enumerate(data):
if c is not ' ':
out[i] = alpha[cypher.index(c)]
print(''.join(out))