Skip to content

Commit

Permalink
Merge pull request keon#95 from ofek/master
Browse files Browse the repository at this point in the history
add matrix transformations
  • Loading branch information
keon authored Jul 28, 2017
2 parents 85a1cb8 + e472519 commit 576b087
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
62 changes: 62 additions & 0 deletions matrix/copy_transform.py
Original file line number Diff line number Diff line change
@@ -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')

0 comments on commit 576b087

Please sign in to comment.