Home > Enterprise >  Rotate martix 90 degrees, clockwise/ without numpy or zip
Rotate martix 90 degrees, clockwise/ without numpy or zip

Time:02-21

my task is: create matrix 3x4 (the user inputs numbers by himself), rotate this matrix 90 degrees (clockwise) so it became 4x3 (according to the task i should use function def_rotate(matrix), pluss i have already used zip, my teacher asked not to use for now, cause we did not pass this in lect, so only def_rotate , no numpy, no zip)

my code works well, but maybe you could help me to optimize it?

def rotate_matrix(source_matrix):
    new_matrix = [[j == 0 for j in range(3)] for i in range(4)]
    for i in range(3):
        for j in range(4):
            new_matrix[j][2-i] = source_matrix[i][j]
    return new_matrix
source_matrix = []
for row_index in range(3):
    list_of_numbers = [int(row_index) for row_index in input(f"Input row with numbers {row_index   1}: ").split(', ')]
    if len(list_of_numbers) == 4:
        source_matrix.append(list_of_numbers)
    else:
        print("incorrect data")
        break
if len(source_matrix) == 3:
    new_matrix = rotate_matrix(source_matrix)
    for i in new_matrix:
        print(*i, sep=" ")


# the output is:
Input row with numbers 1: 1, 11, 2, 4
Input row with numbers 2: 5, 6, 7, 8
Input row with numbers 3: 5, 66, 12, 9

the matrix is:

5 5 1
66 6 11
12 7 2
9 8 4

CodePudding user response:

This is one way to do it:

lst = [[1, 11, 2, 4], [5, 6, 7, 8], [5, 66, 12, 9]]
print(lst)  # Original matrix

for i in range(0, 4):
    row = [] # row of 3x4 matrix
    for j in range(0, 3):
        row.append(lst[j][i])
    row.reverse()  # So that we gat the desired order
    print(row)

Output:

[[1, 11, 2, 4], [5, 6, 7, 8], [5, 66, 12, 9]]
[5, 5, 1]
[66, 6, 11]
[12, 7, 2]
[9, 8, 4]

CodePudding user response:

The problem you describe here is very similar to Leetcode problem 48. Maybe solutions such as this one: https://leetcode.com/problems/rotate-image/discuss/145237/Python-beats-100 help you to get an idea of what you could have done different.

Code is usually optimised in terms of its time or space complexity, in your case however the input is highly constrained which makes optimising those 'less relevant'.

  • Related