-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrids2.py
56 lines (44 loc) · 1.52 KB
/
grids2.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
# playfair grid generator from crib
class Grid:
def __init__(self):
self.positions = {}
self.letters = {}
def getPositionOf(self, letter):
if letter in self.positions:
return self.positions[letter]
else:
return None # raise?
def getLetterAt(self, position):
if position in self.letters:
return self.letters[position]
else:
return "?"
def addLetterAt(self, letter, position):
if letter in self.positions:
del self.positions[letter]
if position in self.letters:
del self.letters[position]
self.letters[position] = letter # sanity check on bounds?
self.positions[letter] = position
def decryptPair(self, p):
p1, p2 = p
if p1 in self.positions:
x1, y1 = self.positions[p1]
else:
return "??"
if p2 in self.positions:
x2, y2 = self.positions[p2]
else:
return "??"
if x1 == x2:
return self.getLetterAt((x1,(y1+1)%5)) + self.getLetterAt ((x2,(y2+1)%5))
elif y1 == y2:
return self.getLetterAt(((x1+1)%5, y1)) + self.getLetterAt (((x2+1)%5, y2))
else:
return self.getLetterAt( (x2, y1)) + self.getLetterAt((x1, y2))
def decrypt(self, s):
s = s.replace(" ", "")
out = ""
while s:
out += self.decryptPair(s[:2])
s = s[2:]