Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A Ceasar cipher encrypts a message by shifting letters in the alphabet. For exam

ID: 3546752 • Letter: A

Question

A Ceasar cipher encrypts a message by shifting letters in the alphabet. For example, a shift of 4 maps 'a' to 'e' and maps 'p' to 't'. Here is a famous line from Shakespeare encrypted with a shift of 4: "vq dg qt pqv vq dg: vjcv ku vjg swguvkqp."

a.) Write a program that takes as input a string to be encrypted and an integer encryption shift (such as 4 mentioned above) and prints the encrypted string. Hint: zip() is helpful in building a dictionary. Also, remember to handle space---it doesn't shift.

b.) Extend your program to take additional input that indicates if your program is to encrypt or decrypt the string.

Explanation / Answer

import string
def cesar_cipher(msg, n, decrypt=False):
   if decrypt: n = -n
   shifted = string.ascii_lowercase[n:] + string.ascii_lowercase[:n]
   char_map = dict(zip(string.ascii_lowercase, shifted))
   return ''.join((char_map[c] if c in char_map else c) for c in msg.lower())
if __name__ == '__main__':
   msg = 'To be or not to be: that is the question.'
   e = cesar_cipher(msg, 2)
   d = cesar_cipher(e, 2, True)
   print(e)
   print(d)



proper indentation: http://ideone.com/JcaR0I

for a), change

def cesar_cipher(msg, n, decrypt=False):
    if decrypt: n = -n

to

def cesar_cipher(msg, n):

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote