changeset 67:4bf2145c16f8

and quick transposition function
author Jeff Hammel <k0scist@gmail.com>
date Sun, 17 Dec 2017 12:53:47 -0800
parents 9f1324a59cc1
children 5916b04d0582
files tvii/transpose.py
diffstat 1 files changed, 28 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /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