# HG changeset patch # User Jeff Hammel # Date 1513544027 28800 # Node ID 4bf2145c16f8f3f555e98a748d32967e6ba39c15 # Parent 9f1324a59cc1641b1bc3414735198549776787c3 and quick transposition function diff -r 9f1324a59cc1 -r 4bf2145c16f8 tvii/transpose.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tvii/transpose.py Sun Dec 17 12:53:47 2017 -0800 @@ -0,0 +1,28 @@ +from .unique import unique +from .unique import NotUnique + + +class NotAMatrix(Exception): + """marker exception for matrix conformity""" + + +def transpose(A): + """transpose a 2D matrix, `A`""" + + if not A: + # empty matrix + return A + + # Asset that all rows have the same length + try: + length = unique([len(row) for row in A]) + except NotUnique as e: + raise NotAMatrix("Multiple number of columns detected: {}".format(sorted(e.multiples))) + + # perform the transpose + transposed = [[None for i in range(len(A))] + for j in range(length)] + for i, row in enumerate(A): + for j, col in enumerate(row): + transposed[j][i] = col + return transposed