This is my solution for ZigZag Conversion, a coding challenge from LeetCode.
The challenge:
Write a program that takes two parameters, a string and a number of rows, that interprets the string as if it were displayed in a zigzag pattern and returns a line by line conversion of this interpretation in a final answer string.
Example:
Given the string 'PAYPALISHIRING', and 3 rows:
P A H N A P L S I I G Y I R
The program should output:
"PAHNAPLSIIGYIR"
My approach was to use a list of dictionaries, with the dictionaries as columns and their position in the list representing row positions. At the end of the control flow the list of dictionaries is unpacked and returned in the final output string.
My solution:
class Solution(object):
def convert(self, s, numRows):
row = numRows
if row <= 1:
return(s)
else:
a_lst = []
a_dict = {}
outer_count = 0
loop_count = 0
my_count = 0
inner_count = row
if row == 2:
minus = 0
else:
minus = 2
for i in s:
loop_count+=1
if outer_count < row:
outer_count+=1
a_dict[outer_count] = i
if outer_count == row:
my_count = 0
inner_count = row
dict_copy = a_dict.copy()
a_lst.append(dict_copy)
a_dict.clear()
elif loop_count == len(s):
dict_copy = a_dict.copy()
a_lst.append(dict_copy)
a_dict.clear()
elif my_count < row - minus:
my_count+=1
if row == 2:
inner_count = my_count
else:
inner_count-=1
a_dict[inner_count] = i
if my_count == row - minus:
outer_count = 0
dict_copy = a_dict.copy()
a_lst.append(dict_copy)
a_dict.clear()
elif loop_count == len(s):
dict_copy = a_dict.copy()
a_lst.append(dict_copy)
a_dict.clear()
my_count = 1
my_str = ''
while my_count <= row:
for d in a_lst:
for key in d:
try:
my_str+=(d[my_count])
break
except KeyError:
break
my_count+=1
return(my_str)
I would like any suggestions on improving code readability or conditional control logic. I would also like to know if I missed any edge cases. Thank you.