def caesar(string, shift):
# We initialize an empty string to which we are going to add the new letters
new_string = ""
# Loop over all the letters in the string
for letter in string:
# We need to make sure that spaces stay intact
if letter == ' ':
new_letter = ' '
else:
# We convert the letter to its ASCII code and add the shift
i = ord(letter) + shift
# We need to make sure that we wrap around the alphabet
if i > ord('z'):
i -= 26
elif i < ord('a'):
i += 26
# We convert the ASCII code back to a letter
new_letter = chr(i)
new_string += new_letter
return new_string
print(caesar("pbatenghyngvbaf lbh unir fhpprrqrq va qrpelcgvat gur fgevat", -13))
Now for the string for which we don't know the shift:
for shift in range(26):
print(shift, caesar("gwc uivioml bw nqvl bpm zqopb apqnb", -shift))
It looks like the right shift was 8! Finally, here's how you could implement your own functions for ord
and chr
. It seems that a
starts at an ASCII code of 97, so let's try and reproduce the results for the letters a
to z
:
def my_ord(s):
letters = 'abcdefghijklmnopqrstuvwxyz'
return letters.index(s) + 97
print(ord('f'), my_ord('f'))
def my_chr(i):
letters = 'abcdefghijklmnopqrstuvwxyz'
return letters[i-97]
print(chr(100), my_chr(100))
Of course, these custom functions will only work for a
to z
and not for any other character or punctuation, but this is just practice for writing functions.