The Caesar cipher was silly. It was effective mainly against illiterate people.
A more serious (but still silly) cipher is a substitution cipher.
In this kind of cipher, any plaintext letter can be mapped to any ciphertext letter.
We'll define one of these below (and eventually see how to crack such a cipher).
## We'll need a copy of the alphabet to work with.## Let's use this as our main alphabetalphabet=tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZ")print(alphabet)## And here we'll make a copy of the alphabet that we don't mind destroying (with pop() operations, for example). alpha_copy=list(alphabet[:])print(alpha_copy)
## In this cell we'll make a "codebook" dictionary similar to the one we made for the Caesar cipher.## Try to understand how it works.importrandomrandom.seed(0)## This will make us all get the same "random" numbers.substitutions=dict()forletterinalphabet:r=random.randint(0,len(alpha_copy)-1)ciphertext_letter=alpha_copy.pop(r)substitutions[letter]=ciphertext_letterprint(substitutions)
## Here is our encoding function. Be sure you understand how it works. defencode(codebook,message):ciphertext=""forletterinmessage:iford(letter)notinrange(ord('A'),ord('Z')+1):print("Invalid message: Only uppercase letters allowed.")returnciphertext+=codebook[letter]returnciphertext
# We practice using the function correctlyencode(substitutions,"ILOVELUCY")
# We also see what happens when we use the function incorrectly.encode(substitutions,"I LOVE LUCY")
Invalid message: Only uppercase letters allowed.
# Use your knowledge of Python string processing to convert the following message into an all caps version with no punctuation or spaces.M="It rained and it rained and it rained. Piglet told himself that never in all his life, and he was goodness knows how old - three, was it, or four? - never had he seen so much rain. Days and days and days. With Piglet trapped by the flood, his Missage in a bottle may be the only hope."importstringstring.punctuation,string.whitespaceM=M.upper()forbadcharin(string.punctuation+string.whitespace):M=M.replace(badchar,'')M
## Don't run this cell!print(encode(substitutions,M))## In case you do, here's what it said:C='ENEOENFLEOKFXAQNOFDEMTPXOQONPOKPOPOJEOHEXIVWFVWQXKEOKIPHOSFMVMPOPUEMCWPPNAEMVFXEVESFFNFZFOWFDPOEMCWPNEXMWQYVPVWFDFMVAQOMVFXMCWPPNWFDFOVPOVPEVVFOKCEATXQKSFHOQZFXMQVIEOKTFCEAFVWFFKQVPXPUVWFHOKFXSXEKHEVFYEYFXSXEOVEEUVFXSXEKHEVQOSUXPACEATXQKSFQOAQNOFAPZFKTECGVPNPOKPODQVWFOPHSWMEZQOSMVPNQZFUPXPOFIFEXWFDEMKFVFXAQOFKVPTFCPAFEDXQVFXTIWFWEKTFFOPUUFXFKVWFYPMQVQPOPUEMMQMVEOVFKQVPXEVYHOCWECNEMMQCTXQVQMWWHAPXAESERQOFWFXFAEQOFKEVYHOCWUPXVWFOFLVFQSWVIFEXM'