How to Transpose a string matrix in python without numpy

--

I was solving the problem GridChallenge on HackerRank. In hacker rank sometimes you are not allowed to import numpy. I wanted to transpose a square matrix nonetheless, so I came up with this method which I am happy to share.



#Transpose Function in Python
def get_i (somestringlist,i): return somestringlist [i]
def get_col_i (grid,j) : return "".join (list (map (get_i , grid , [j for p in range ( len (grid) ) ] ) ))
def t_grid (grid):
grid_list = [grid for i in range (len (grid[0]) )]
index_list = [i for i in range (len (grid[0]))]
return list (map (get_col_i , grid_list , index_list))

#Example test Case
from time import time
start = time ()
grid = ["aepo",
"poip",
"iope"]
trans_grid = t_grid(grid)
end = time ()
process_time = end - start
print (trans_grid , process_time )
print (process_time * 1000000)

It would take about 17 seconds to transpose a 1 million rows matrix of 4 letters text.

Thank you for your interest and please leave in the comments if you would like any further elaboration on the code. I just tried to keep the solution compact but I can elaborate on its logic and implementation if required.

--

--

Emad Ezzeldin ,Sr. DataScientist@UnitedHealthGroup
Emad Ezzeldin ,Sr. DataScientist@UnitedHealthGroup

Written by Emad Ezzeldin ,Sr. DataScientist@UnitedHealthGroup

5 years Data Scientist and a MSc from George Mason University in Data Analytics. I enjoy experimenting with Data Science tools. emad.ezzeldin4@gmail.com

Responses (2)