In python write a function
How the Encryption is done:
In the program, first a grid is made, where number of rows is given and number of columns is such that it can store the whole 'plaintext' (There can be extra spaces left in the grid other than 'plaintext'). Number of columns is calculated using ceil function.
The plaintext is stored in the grid in following manner.
1st letter of plaintext | 10th letter | 11th letter |
2nd letter | 9th letter | last letter |
3rd letter | 8th letter | |
4th letter | 7th letter | |
5th letter | 6th letter |
Table 1
The empty spaces are filled with '%' and then the whole grid is added from first row then second row ... to get the "encrypted word".
For example: 'america' , num_rows = 4
then, num_col = 2
a | % |
m | a |
e | c |
r | i |
Table 2
So the encrypted word is 'a%maecri'
So how to decrypt:
First we make the grid from the encrypted word. This can be easily just reverse as Table 2.
Now to get decryption, we move in the grid as in Table 1 and add letters to decrypted string(which is intially ""). We return decrypted string when we first get the '%' beacuse after that there is no need to go.
Points to note:
1. We have to run a initial loop as number of times as number of column.
2. Not in even columns, we have to move from up to down in the column(through rows) and in odd columns we have to move from down to up.
Here is the code:
import math
def sbu_decrypt(encrypted,num_rows):
if num_rows
<=0:
#Return encrypted if num_rows<=0
return encrypted
if
encrypted=="":
#Return None id encrypted is empty string
return None
num_cols =
len(encrypted)//num_rows #Get num_cols. (Note
that len(encrypted)=num_rowss*num_cols)
k = 0
grid = [['' for i in range(num_cols)] for j in
range(num_rows)] #Make a grid
'''Fill the grid from encrypted'''
for i in range(num_rows):
for j in
range(num_cols):
grid[i][j] = encrypted[k]
k+=1
decrypted =
""
#Empty string to store decrypted letters
'''In even columns move from top to bottom
And in odd columns move from bottom to
top'''
for col in range(num_cols):
if col%2 == 0:
row = 0
else:
row = num_rows-1
k = 0
while(k<num_rows): #Moving
in a column(through rows)
if grid[row][col]=="%":
return decrypted #Retirn
whenever % is encountered
decrypted+=grid[row][col]
if col%2 == 0:
row+=1
else:
row-=1
k+=1
return decrypted
print(sbu_decrypt('AMERICA',7))
print(sbu_decrypt('SOO%TRK%OBUVNYNI',4))
print(sbu_decrypt('CHICKENWINGS',-2))
print(sbu_decrypt('',5))
print(sbu_decrypt('Srs%tei%ovt%niy%ynN%BUekrkwrooYo',8))
print(sbu_decrypt('UtetasOmecanidStefAri%',2))
Screenshots:
Output:
Get Answers For Free
Most questions answered within 1 hours.