Skip to content

Instantly share code, notes, and snippets.

@jon-dearaujo
Last active August 22, 2019 13:45
Show Gist options
  • Select an option

  • Save jon-dearaujo/b953fb865f2f992e808297441fb517ea to your computer and use it in GitHub Desktop.

Select an option

Save jon-dearaujo/b953fb865f2f992e808297441fb517ea to your computer and use it in GitHub Desktop.
Flip a numeric matrix with Python 3.
def _flip_matrix(matrix, n_90_degrees_flips):
'''
Let's say that we have the following matrix:
1 , 2 , 3 , 4
5 , 6 , 7 , 8 => [[1 , 2 , 3 , 4], [5 , 6 , 7 , 8], [9 , 10, 11, 12], [13, 14, 15, 16]]
9 , 10, 11, 12
13, 14, 15, 16
And we want to flip it 1x in a way that it looks like the following
13, 9 , 5, 1
14, 10, 6, 2
15, 11, 7, 3
16, 12, 8, 4
This function takes the square matrix and the number of flips it must perform
as parameters and returns a new matrix
'''
for i in (range(n_90_degrees_flips)):
matrix = swap_lines(transpose(matrix))
return matrix
def transpose(matrix):
# Creating the matrix to receive the transposition
number_of_lines = len(matrix[0])
number_of_columns = len(matrix)
transpose = [[0 for i in range(number_of_columns)] for i in range(number_of_lines)]
for i in range(number_of_lines):
for j in range(number_of_columns):
# Each item in the original array is being placed in the transpose
# in the correct position
transpose[i][j] = matrix[j][i]
return transpose
def swap_lines(matrix):
matrix_len = len(matrix)
for i in range(matrix_len):
line_len = len(matrix[i])
first_index = 0
last_index = line_len - 1
while last_index > first_index:
# swaping the numbers between first_index and last_index without aux
matrix[i][first_index] += matrix[i][last_index]
matrix[i][last_index] = matrix[i][first_index] - matrix[i][last_index]
matrix[i][first_index] = matrix[i][first_index] - matrix[i][last_index]
#first_index is incremented by one each roung
first_index += 1
# last_index is decremented by one each round
last_index -= 1
return matrix
def print_matrix(m):
for i in range(len(m)):
print(m[i])
# original = [[1 , 2 , 3 , 4], [5 , 6 , 7 , 8], [9 , 10, 11, 12], [13, 14, 15, 16]]
original = [[1,2 ,3], [4,5,6],[7,8,9],[10,11,12]]
print_matrix(original)
print("-------")
print_matrix(_flip_matrix(original, 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment