Skip to content

Instantly share code, notes, and snippets.

@Himan10
Created August 20, 2020 07:51
Show Gist options
  • Select an option

  • Save Himan10/75a2608d7ac9bc22d084432b1479f4ca to your computer and use it in GitHub Desktop.

Select an option

Save Himan10/75a2608d7ac9bc22d084432b1479f4ca to your computer and use it in GitHub Desktop.
Convert a normal string into a zig_zag format
## Convert a normal string into a zig-zag form
import numpy as np
class Solution:
def convert(self, string:str, numRows:int) -> tuple:
if numRows < 1:
return string
numCol = round(len(string)/numRows)+1
if numCol < 1:
return string
stacks = [[] for i in range(0, numCol)]
#additional = []
additionalCount = numRows-2
w = 0
for i in range(len(stacks)):
stacks[i].extend(string[w:w+numRows])
w += numRows
if len(stacks[i]) == numRows:
"""for those characters which will form the zig-zag structure
or say, diagonal structure"""
try:
temp = additionalCount
while temp > 0:
stacks[i][temp] = list(stacks[i][temp]) # add those char. with their partner character
stacks[i][temp].append(string[w])
temp -= 1
w += 1
except:
pass
else:
# Fill None if there's nothing to add & len of that stack is less than numRow
stacks[i].extend([None]*(numRows - len(stacks[i])))
print(stacks)
def zigzagToString(stacks: list, n: int) -> str:
""" build a zigzag string """
new_string = ""
# convert a list into matrix
stacks = np.array(stacks)
for i in range(n):
for j in stacks[:, i]:
if j is None:
pass
elif type(j) == list:
new_string += ''.join(j)
else:
new_string += j
return new_string
return zigzagToString(stacks, numRows)
if __name__ == "__main__":
s = Solution()
while True:
string = str(input(" Enter string : "))
numRows = int(input(" Enter Rows : "))
print(s.convert(string, numRows))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment