2

I've been trying to figure out how to transpose a matrix (represented as a list of lists) in Python using map and filter only recursively. I;ve tried various implementations and none of them work. Here's what I have currently:

def transpose(matrix):
    return list(map(lambda x: [x], list(filter(lambda x: [0], matrix))))

All other answers using for loops and/or zip functions which is a restriction.

Any directions would be helpful too

  • @E.Coms: Not a duplicate, "recursively" is not a usual part of transposition, and not present in your link (even though OP doesn't have any recursion in their code?) – Amadan Oct 19 '18 at 02:18
  • Yeah all the duplicates use some form or zip or for loop.. – ilovesports524 Oct 19 '18 at 02:19
  • @blhsing see above – Amadan Oct 19 '18 at 02:19
  • @blhsing Not a duplicate. He asked to transpose using *only* `lambda` and `filter`. – Rocky Li Oct 19 '18 at 02:20
  • Indeed. Sorry about that. Reopened then. – blhsing Oct 19 '18 at 02:21
  • Thanks! Anyone have any ideas on how I could go from here? I am thinking I must map through the nested lists with a filter inside that extracts each indexed positioned element although my execution is lacking.. – ilovesports524 Oct 19 '18 at 02:25
  • @RockyLi I don't think it's only lambda and filter; I read it "using map and filter, only recursively" where "only" means "just" or "but". Then again, OP should likely clarify what the exact limits are. Note that there is no natural way to transpose a matrix recursively; it is possible, but cannot be particularly fast, I don't think. – Amadan Oct 19 '18 at 02:25
  • @Amadan yes you're right, it just struck me as particularly interesting as a code golf kind of question. – Rocky Li Oct 19 '18 at 02:26

2 Answers2

3

You can map the first column of each row as a sub-list (to become a new row), and then recursively pass the rest of the matrix (without the first column) to the same process, until all rows are empty:

def transpose(m):
    return m and [list(map(lambda r: r[0], m)), *transpose(list(filter(len, map(lambda r: r[1:], m))))]

so that:

transpose([[1,2,3],[3,4,5]])

returns:

[[1, 3], [2, 4], [3, 5]]
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

Got it:

list(map(lambda i: list(map(lambda x: x[i], matrix)), range(len(matrix[0]))))

No for loop in this one.

Rocky Li
  • 5,641
  • 2
  • 17
  • 33