The point is that you must understand when cursor move straight down through the line, the row index is increasing. However, when cursor is moving diagonally the row index is decreasing. So we can use divmod function in Python to get current status of cursor for whether is moving straight or diagonally and current character should be in which row. Hope this explanation is clear.
def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1: return s n = len(s) ref = [ for _ in range(numRows)] cur = 0 while cur < n: mode, rem = divmod(cur, numRows - 1) if mode % 2 == 0: ref[rem].append(s[cur]) else: ref[numRows - 1 - rem].append(s[cur]) cur += 1 return ''.join(reduce(lambda x, y : x + y, ref))