Chapter 5 String Algorithms
59
For example, suppose there is a flight from New York to Lima, Peru, that leaves at 9 p.m.
Suppose
the two cities are in the same time zone, and the flight takes eight hours.
What time will the flight
arrive? Nine plus 8 is 17, but a 12- hour clock doesn’t show 17. To determine the arrival time,
you add
9 and 8 (17) and perform modulo 12 on the result.
17 % 12
Twelve divides into 17 one time, with a remainder of 5, which means the flight will arrive at 5 a.m.
(Figure 5.2).
Modular arithmetic is helpful when you are writing any program involving time. For example, if
you were building a website
for processing flight times, you could use modular arithmetic to figure
out what time a flight will land.
Now that you understand
how modular arithmetic works, you can code a Caesar cipher by writing
a function that takes a string and a number to shift each letter
by and outputs a new, encrypted string:
import string
def cipher(a_string, key):
uppercase = string.ascii_uppercase
lowercase = string.ascii_lowercase
encrypt = ''
for c in a_string:
if c in uppercase:
new = (uppercase.index(c) + key) % 26
encrypt += uppercase[new]
elif c in lowercase:
new = (lowercase.index(c) + key) % 26
encrypt += lowercase[new]
else:
encrypt += c
return
encrypt
12
3
9
10
2
11
1
8
6
7
5
4
Figure 5.2: Eight hours after 9 is 5.