0

Since I'm here, might as well get all the help I can. NOTE: I believe this is different from other problems involving transposing with arrays.

Like in my first post, I have been looking into recursion in Python, and have been attempting to solve problems with normally simple solutions via loops, etc., but instead solving them with recursive algorithms.

For this particular problem, given a 2D array formatted in an NxN grid, I want to take each column from this grid and turn them into the rows of a new grid.

As an example, let's say I pass in a grid: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

My program should take the column [1, 5, 9, 13] and make it the row of a new 2D array; below is a visualization:

[[1, 2, 3, 4],           [[1, 5, 9, 13], 
 [5, 6, 7, 8],     ---->  [2, 6, 10, 14], 
 [9, 10, 11, 12],  ---->  [3, 7, 11, 15], 
 [13, 14, 15, 16]]        [4, 8, 12, 16]]

What now follows is my attempt using a helper function to extract each column, and a helper to create an n value that needs to be passed into it:

def get_column(array, n):

    base_val = array[0][n]

    if len(array) == 1:
        return [base_val]
    else:
        return [base_val] + get_column(array[1:], n)

def integer(grid):
    return len(grid)

def transpose(grid, n = integer(grid), new_grid = []):

    if n < len(grid):
        new_grid.append(get_column(grid, n))
        n += 1
        return transpose(grid, n, new_grid)
    else:
        return new_grid

The only call from the outside in my main() function is to the transpose() function passing through only the grid as an argument.

1 Answers1

0

In python, list is actually structured as a dynamic array. It means that you need O(n) time to access the n-element. So transposing using a list selection approach would not achieve the vectorised effect.

How does NumPy's transpose() method permute the axes of an array?

has explained what numpy.transpose has done to optimize the transpose operation.

chrisckwong821
  • 1,133
  • 12
  • 24
  • Oh, yes, I am aware of numpy from having already looked for an answer to my problem. However, I decided to post my question since I am not looking for a solution in that vein; while numpy would certainly accomplish this, I'm attempting this particular recursive manner to improve my understanding of the concept. (practice makes perfect, after all!) – The Popcultureman Oct 27 '19 at 02:45