Answer:
The code is given below with appropriate comments
Explanation:
CIPHER = (("D", "A", "V", "I", "O"),
("Y", "N", "E", "R", "B"),
("C", "F", "G", "H", "K"),
("L", "M", "P", "Q", "S"),
("T", "U", "W", "X", "Z"))
# Add your code here!
def encrypt(plaintext):
theList = []
for char in plaintext:
if char.isalpha():
char = char.upper()
if char == "J":
char = "I"
theList.append(char)
if len(theList) % 2 == 1:
theList.append("X")
for i in range(0, len(theList), 2):
if theList[i] == theList[i + 1]:
theList[i + 1] = "X"
findex = [-1, -1]
sindex = [-1, -1]
for j in range(len(CIPHER)):
for k in range(len(CIPHER)):
if theList[i] == CIPHER[j][k]:
findex = [j, k]
if theList[i + 1] == CIPHER[j][k]:
sindex = [j, k]
# same row
if (findex[0] == sindex[0]):
findex[1] += 1
sindex[1] += 1
if findex[1] == 5:
findex[1] = 0
if sindex[1] == 5:
sindex[1] = 0
theList[i] = CIPHER[findex[0]][findex[1]]
theList[i + 1] = CIPHER[sindex[0]][sindex[1]]
# same column
elif (findex[1] == sindex[1]):
findex[0] += 1
sindex[0] += 1
if findex[0] == 5:
findex[0] = 0
if sindex[0] == 5:
sindex[0] = 0
theList[i] = CIPHER[findex[0]][findex[1]]
theList[i + 1] = CIPHER[sindex[0]][sindex[1]]
else:
theList[i] = CIPHER[findex[0]][sindex[1]]
theList[i + 1] = CIPHER[sindex[0]][findex[1]]
return "".join(theList)
def decrypt(ciphertext):
theString = ""
findex = [-1, -1]
sindex = [-1, -1]
for i in range(0, len(ciphertext), 2):
for j in range(len(CIPHER)):
for k in range(len(CIPHER)):
if ciphertext[i] == CIPHER[j][k]:
findex = [j, k]
if ciphertext[i + 1] == CIPHER[j][k]:
sindex = [j, k]
if (findex[0] == sindex[0]):
findex[1] -= 1
sindex[1] -= 1
if findex[1] == -1:
findex[1] = 4
if sindex[1] == -1:
sindex[1] = 4
theString += CIPHER[findex[0]][findex[1]]
theString += CIPHER[sindex[0]][sindex[1]]
# same column
elif (findex[1] == sindex[1]):
findex[0] -= 1
sindex[0] -= 1
if findex[0] == -1:
findex[0] = 4
if sindex[0] == -1:
sindex[0] = 4
theString += CIPHER[findex[0]][findex[1]]
theString += CIPHER[sindex[0]][sindex[1]]
else:
theString += CIPHER[findex[0]][sindex[1]]
theString += CIPHER[sindex[0]][findex[1]]
return theString
# Below are some lines of code that will test your function.
# You can change the value of the variable(s) to test your
# function with different inputs.
#
# If your function works correctly, this will originally
# print: QLGRQTVZIBTYQZ, then PSHELXOWORLDSX
print(encrypt("PS. Hello, worlds"))
print(decrypt("QLGRQTVZIBTYQZ"))