From e4725199aa044c8d2b52f2c209d17719460b08e2 Mon Sep 17 00:00:00 2001 From: ofek Date: Sun, 2 Jul 2017 00:02:26 -0400 Subject: [PATCH] add matrix transformations --- README.md | 1 + matrix/copy_transform.py | 62 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 matrix/copy_transform.py diff --git a/README.md b/README.md index 93949183d..a7230db78 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,7 @@ Minimal and clean example implementations of data structures and algorithms in P - [pythagoras](math/pythagoras.py) - [matrix](matrix) - [matrix_rotation.txt](matrix/matrix_rotation.txt) + - [copy_transform](matrix/copy_transform.py) - [bomb_enemy](matrix/bomb_enemy.py) - [rotate_image](matrix/rotate_image.py) - [sparse_dot_vector](matrix/sparse_dot_vector.py) diff --git a/matrix/copy_transform.py b/matrix/copy_transform.py new file mode 100644 index 000000000..772a81c9c --- /dev/null +++ b/matrix/copy_transform.py @@ -0,0 +1,62 @@ +def rotate_clockwise(matrix): + new = [] + for row in reversed(matrix): + for i, elem in enumerate(row): + try: + new[i].append(elem) + except IndexError: + new.insert(i, []) + new[i].append(elem) + return new + +def rotate_counterclockwise(matrix): + new = [] + for row in matrix: + for i, elem in enumerate(reversed(row)): + try: + new[i].append(elem) + except IndexError: + new.insert(i, []) + new[i].append(elem) + return new + +def top_left_invert(matrix): + new = [] + for row in matrix: + for i, elem in enumerate(row): + try: + new[i].append(elem) + except IndexError: + new.insert(i, []) + new[i].append(elem) + return new + +def bottom_left_invert(matrix): + new = [] + for row in reversed(matrix): + for i, elem in enumerate(reversed(row)): + try: + new[i].append(elem) + except IndexError: + new.insert(i, []) + new[i].append(elem) + return new + +if __name__ == '__main__': + def print_matrix(matrix, name): + print('{}:\n['.format(name)) + for row in matrix: + print(' {}'.format(row)) + print(']\n') + + matrix = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + ] + + print_matrix(matrix, 'initial') + print_matrix(rotate_clockwise(matrix), 'clockwise') + print_matrix(rotate_counterclockwise(matrix), 'counterclockwise') + print_matrix(top_left_invert(matrix), 'top left invert') + print_matrix(bottom_left_invert(matrix), 'bottom left invert')