Practice Problem - Cryptography

Cryptography is the study of how to make messages secret or how to read secret messages. A very simple encryption technique is called the Caesar cipher, which you can read up more about here. The basic idea is that each letter is replaced by a letter that is a certain number of letters away, so for example if the shift was 2, then A would become C, B would become D, etc. (and Z will become B).

As we will learn in more detail tomorrow, you can write your own functions in Python, the simplest of which can take the form:

In [1]:
def encrypt(string):
    # do things here
    return new_string

Write a function that given a string and a shift, will return the encrypted string for that shift. Note that the same function can be used to decrypt a message, by passing it a negative shift.

The rules are: you should only accept and return lowercase letters, and spaces should not be changed.

Then, decrypt the following message, which was encrypted with a shift of 13:

pbatenghyngvbaf lbh unir fhpprrqrq va qrpelcgvat gur fgevat    

Now if you are up for a challenge, try and decrypt this and find the shift:

gwc uivioml bw nqvl bpm zqopb apqnb

Hint: there are several ways you can convert between letters and numbers. One is to use the built-in functions chr and ord (and remember you can find out more about a function by using ? in IPython). Another is to set up the alphabet in a string and use item access ([4]) to convert from numbers to letters, and the index method to convert from letters to numbers.

Solution

In [2]:
# your solution here