Given a two-dimensional list, say some_list = ["ABCD", "EFGH", "IJ"]
, I am supposed to encrypt it by reading each column top to bottom, thus:
A B C D E F G H I J
Would become:
AEI BFJ CG DH
My initial try had “index out of range” problem so I did this:
def encrypt_list(some_list): encrpted_list = [] for i in range(c): string = "" for j in range(f): string += my_list[j][i:i + 1] encrpted_list.append(string) return encrpted_list
Which looks like a hack. Is there a more Pythonic way?
(This is essentially the Encryption problem from HackerRank.)
Complete working code:
import math
s = "feedthedog"
length_s = len(s)
f = math.floor(math.sqrt(length_s))
c = math.ceil(math.sqrt(length_s))
if c * f < length_s:
f = c
def chunks(string, split_point):
for start in range(0, len(string), split_point):
yield s[start:start + split_point]
split_list = [chunk for chunk in chunks(s, c)]
def encrypt_list(my_list):
encrpted_list = []
for i in range(c):
string = ""
for j in range(f):
string += my_list[j][i:i + 1]
encrpted_list.append(string)
return encrpted_list
solution_list = encrypt_list(split_list)
for item in solution_list:
print(item, end=" ")