• + 0 comments

    Python3

    `

    def encryption(s):
            # Write your code here
            s_list = list(s)
            dim = math.sqrt(len(s_list))
            # matrix dimensions
            rows = math.floor(dim)
            cols = math.ceil(dim)
            # exception
            if (len(s_list) - (rows * cols)) > 0:
                    rows = math.ceil(dim)
                    cols = math.ceil(dim)
            # organize values in matrix
            matrix = [[None] * cols for _ in range(rows)]
            s_iter = iter(s_list)
            for row in range(rows):
                    for col in range(cols):
                            matrix[row][col] = next(s_iter, "")
            # extract values from matrix: answer
            ans = []
            for col in range(cols):
                    for row in range(rows):
                            ans.append(matrix[row][col])
                            if row == rows-1:
                                    ans.append(" ")
                            else:
                                    continue
            return "".join(ans)