Python Forum
Monoalphabetic cipher - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Monoalphabetic cipher (/thread-17194.html)



Monoalphabetic cipher - pawlo392 - Apr-01-2019

Hello!
I wrote this code:
keys={'a':'z','b':'y','c':'x','d':'w','e':'v','f':'u','g':'t','h':'s','i':'r','j':'q','k':'p','l':'o','m':'n'}
reverse_keys={}
for key,value in keys.items():
    reverse_keys[value]=key
def encrypt(text):
    text=str(text)
    encrypting=[]
    for l in text:
        encrypting.append(keys.get(l,l))
    print(''.join(encrypting))
def decipher(text):
    text=str(text)
    decrypted=[]
    for l in text:
        decrypted.append(reverse_keys.get(l,l))
    print(''.join(decrypted))
print(encrypt("hej"))
print(decipher("svq"))
But now I want to create a function encrypt(text,keys) for example encrypt(hej,"zyxwvutsrqponmlkjihgfedcba"). I want the user to define the key himself.


RE: Monoalphabetic cipher - ichabod801 - Apr-01-2019

I would make keys a parameter to decipher, with a default (as a string like in your desired example) equivalent to what the global variable is now. Convert that to a dictionary like keys is now, and use that for encryption. Of course, first you need to fix the fact that your keys only cover half the dictionary, so only half the letters get encrypted.