Transpose (Python)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Haskell | Python

[edit] Iteration

<<transpose_iteration.py>>=
def transpose(matrix):
    newMatrix = []
    for i in range(len(matrix[0])):
        newVector = []
        for vector in matrix:
            newVector.append(vector[i])
        newMatrix.append(newVector)
    return newMatrix

[edit] Recursive

<<transpose_recursive.py>>=
def transpose(matrix):
    if matrix[0]:
        return [map(lambda vector: vector[0], matrix)] +\
            transpose(map(lambda vector: vector[1:], matrix))
    else:
        return [] 

[edit] Functional

<<transpose_functional.py>>=
def transpose(matrix):
    return map(lambda i: map(lambda vector: vector[i], matrix),
        [i for i in range(len(matrix[0])-1])
Download code
hijacker
hijacker
hijacker
hijacker