The Self-Taught Computer Scientist


Introduction to Algorithms


Download 1.48 Mb.
Pdf ko'rish
bet54/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   50   51   52   53   54   55   56   57   ...   147
Bog'liq
books-library.net-11301817Az7X6

Introduction to Algorithms
60
Your function, 
cipher
, accepts two parameters: 
a_string
, which is the string you want to encrypt, 
and 
key
, the number of places you are shifting each letter.
You start by using Python’s built- in 
string
module to create two strings that contain every character 
in the alphabet in both uppercase and lowercase:
import string
def cipher(a_string, key): 
uppercase = string.ascii_uppercase
lowercase = string.ascii_lowercase
If you print uppercase and lowercase, the output looks like this:
>> 'abcdefghijklmnopqrstuvwxyz'
>> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Next, you create the variable 
encrypt
, which starts as an empty string but later will hold your 
encrypted string:
encrypt = ''
Then, you iterate through your string, keeping track of each character in the variable 
c
:
for c in a_string:
If the character is uppercase, you find the character’s index in 
uppercase
(which, remember, is 
ABCDEFGHIJKLMNOPQRSTUVWXYZ
). Then you add 
key
to that index, which will give you the new, encrypted 
character. For example, if the character is 
A and 
key
is 2, first, you get the index of 
A in 
uppercase

which is index 0, and then add 2. Index 2 in 
uppercase
is the letter 
C.
There is a problem with using this method to get the new character, though. What happens if you 
shift the letter 
Z one or more places? The letter Z is at index 25. If you add 2 to 25, you get index 27, 
which does not exist. Because 
Z is the last letter in the alphabet, you need to go to the alphabet’s 
beginning to get the new, encrypted character. In this case, you need to get index 2, which is 
C 
(index 0 + 2).
You solve this by using modulo 26 on the sum of each character’s starting index plus 
key
. First, 
you get the character’s starting index in 
uppercase
. Then, you add 
key
and perform modulo 26.
if c in uppercase:
new = (uppercase.index(c) + key) % 26
This code works because you are using modular arithmetic to “wrap around” whenever you reach 
a certain value. In this situation, you “wrap around” whenever your index exceeds 25.
Once you have the new index for the encrypted character, you use it to look up what character it 
is in 
uppercase
and store it in the variable 
encrypt
.



Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   50   51   52   53   54   55   56   57   ...   147




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling