I learned the CaesarCipher:
In [90]: !cat caesar_cipher.py
class CaesarCipher:
"""Construct Caesar cipher using given integer shift for rotation."""
def __init__(self, shift):
encoder = [None] * 26
decoder = [None] * 26
for k in range(26):
encoder[k] = chr((k + shift)%26 + ord('A'))
decoder[k] = chr((k - shift)%26 + ord('A')) #find the number of Letters
self.encoder = "".join(encoder)
self.decoder = "".join(decoder)
def encrypt(self, message):
print(self.encoder)
return self._transform(message, self.encoder)
def decrypt(self, message):
return self._transform(message, self.decoder)
def _transform(original, code):
msg = list(original)
for k in range(len(msg)):
j = ord(msg[k]) - ord('A')
msg[k] = code[j]
return "".join(msg)
if __name__ == "__main__":
cipher = CaesarCipher(3)
message = "THE EAGLE IS IN PLAY; MEET AT JOE'S."
coded = cipher.encrypt(message)
print("Secret: ", coded)
answer = cipher.decrypt(coded)
print("Message: ", answer)
It report error on _trasform
In [91]: !python caesar_cipher.py
DEFGHIJKLMNOPQRSTUVWXYZABC
Traceback (most recent call last):
File "caesar_cipher.py", line 29, in <module>
coded = cipher.encrypt(message)
File "caesar_cipher.py", line 14, in encrypt
return self._transform(message, self.encoder)
TypeError: _transform() takes 2 positional arguments but 3 were given
"_transform() takes 2 positional arguments" and I did give 2 arguments
Why it report 3 were given?
You need to define it as
def _transform(self, original, code)
You have to add self
argument at first, like
def _transform(self, original, code)...
Or you can also make it as a staticmethod.
@staticmethod
def _transform(original, code)...
There is no need to have _transform()
method in the CaesarCipher
class, because it is a stateless one (as it don't use instance variables) and it is has no particular relation to Ceasar Cipher - it is a generic character substitution cipher.
So you may define it as a regular function (outside of any class) and instead of commands
return self._transform(message, self.encoder)
return self._transform(message, self.decoder)
(in your encrypt()
and decrypt()
methods) use
return transform(message, self.encoder)
return transform(message, self.decoder)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With