forked from 4dsolutions/Python5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpx_class.py
More file actions
228 lines (200 loc) · 6.24 KB
/
px_class.py
File metadata and controls
228 lines (200 loc) · 6.24 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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# -*- coding: utf-8 -*-
"""
Last updated Jan 10, 2016
@author: Kirby Urner
(c) MIT License
Fun for Group Theory + Python
https://github.com/4dsolutions/Python5/blob/master/px_class.py
"""
from random import shuffle
from string import ascii_lowercase # all lowercase letters
class P:
"""
A Permutation
self._code: a dict, is a mapping of iterable elements
to themselves in any order.
"""
def __init__(self,
the_code = None, # direct inject
inv_table = None, # construct
iterable = ascii_lowercase + ' '): # default domain
"""
start out with Identity, or directly inject the mapping as
a dict or use an inversions table to construct the permutation
"""
if the_code:
self._code = the_code
elif inv_table:
values = []
for key in sorted(inv_table, reverse=True):
if inv_table[key] >= len(values):
values.append(key)
else:
values.insert(inv_table[key], key)
self._code = dict(zip(sorted(inv_table), values))
elif iterable:
if not "__iter__" in dir(iterable):
raise TypeError
self._code = dict(zip(iterable, iterable))
def shuffle(self):
"""
return a random permutation of this permutation
"""
# use shuffle
# something like
the_keys = list(self._code.keys()) # grab keys
shuffle(the_keys) # shuffles other one
newP = P()
newP._code = dict(zip(self._code.keys(), the_keys))
return newP
def encrypt(self, plain):
"""
turn plaintext into cyphertext using self._code
"""
output = "" # empty string
for c in plain:
output = output + self._code.get(c, c)
return output
def decrypt(self, cypher):
"""
Turn cyphertext into plaintext using ~self
"""
reverse_P = ~self # invert me!
output = ""
for c in cypher:
output = output + reverse_P._code.get(c, c)
return output
def __getitem__(self, key):
return self._code.get(key, None)
def __repr__(self):
return "P class: " + str(tuple(self._code.items())[:3]) + "..."
def cyclic(self):
"""
cyclic notation, a compact view of a group
"""
output = []
the_dict = self._code.copy()
while the_dict:
start = tuple(the_dict.keys())[0]
the_cycle = [start]
the_next = the_dict.pop(start)
while the_next != start:
the_cycle.append(the_next)
the_next = the_dict.pop(the_next)
output.append(tuple(the_cycle))
return tuple(output)
def __mul__(self, other):
"""
look up my keys to get values that serve
as keys to get others "target" values
"""
new_code = {}
for c in self._code: # going through my keys
target = other._code[ self._code[c] ]
new_code[c] = target
new_P = P(' ')
new_P._code = new_code
return new_P
def __truediv__(self, other):
return self * ~other
def __pow__(self, exp):
"""
multiply self * self the right number of times
"""
if exp == 0:
output = P()
else:
output = self
for x in range(1, abs(exp)):
output *= self
if exp < 0:
output = ~output
return output
def __call__(self, s):
"""
another way to encrypt
"""
return self.encrypt(s)
def __invert__(self):
"""
create new P with reversed dict
"""
newP = P(' ')
newP._code = dict(zip(self._code.values(), self._code.keys()))
return newP
def __eq__(self, other):
"""
are these permutation the same?
Yes if self._code == other._code
"""
return self._code == other._code
def inversion_table(self):
invs = {}
invP = ~self
keys = sorted(self._code)
for key in keys:
x = invP[key] # position of key
cnt = 0
for left_of_key in keys: # in order up to position
if left_of_key == x: # none more to left
break
if self._code[left_of_key] > key:
cnt += 1
invs[key] = cnt
return invs
if __name__ == "__main__":
p = P() # identity permutation
new_p = p.shuffle()
inv_p = ~new_p
try:
assert p == inv_p * new_p # should be True
print("First Test Succeeds")
except AssertionError:
print("First Test Fails")
#==========
p = P().shuffle()
try:
assert p ** -1 == ~p
assert p ** -2 == ~(p * p)
assert p ** -2 == (~p * ~p)
print("Second Test Succeeds")
except AssertionError:
print("Second Test Fails")
#==========
p = P().shuffle()
s = "able was i ere i saw elba"
c = p(s)
print("Plain: ", s)
print("Cipher: ", c)
try:
assert p.decrypt(c) == s
print("Third Test Succeeds")
except AssertionError:
print("Third Test Fails")
#==========
knuth = {1:5, 2:9, 3:1, 4:8, 5:2, 6:6, 7:4, 8:7, 9:3} # vol 3 pg. 12
expected = {1:2, 2:3, 3:6, 4:4, 5:0, 6:2, 7:2, 8:1, 9:0} # Ibid
k = P(the_code=knuth)
try:
assert k.inversion_table() == expected
print("Fourth Test Succeeds")
except AssertionError:
print("Fourth Test Fails")
#==========
p = P(inv_table = expected)
try:
assert p == k
print("Fifth Test Succeeds")
except AssertionError:
print("Fifth Test Fails")
#==========
p = P().shuffle()
inv = p.inversion_table()
print("Perm:", p._code)
print("Inv table:", inv)
new_p = P(inv_table = inv)
try:
assert p == new_p
print("Sixth Test Succeeds")
except AssertionError:
print("Sixth Test Fails")