简体   繁体   中英

Array in-place rotater returning wrong values

I wish to define a function to rotate a matrix by 90 degrees in place

def rotate_matrix(matrix):
        for i in range(len(matrix)//2):
            for j in range(i, len(matrix)-i-1):
                matrix[~j][i], matrix[i][j], matrix[j][~i], matrix[~i][~j] = matrix[i][j], matrix[j][~i], matrix[~i][~j], matrix[~j][i]
        return matrix

When inserting :

[
 [a, b],
 [c, d]
]

it returns:

[
 [b, d],
 [a, c]
]

instead of:

[
 [c, a],
 [d, b]
]

and I'm unsure why.

You were on the right track! Your code performs a counterclockwise rotation instead of clockwise .
To solve it you have to make a few small changes to the assignment logic:

def rotate_matrix(matrix):
        for i in range(len(matrix)//2):
            for j in range(i, len(matrix)-i-1):
                matrix[~j][i], matrix[i][j], matrix[j][~i], matrix[~i][~j] = \
                matrix[~i][~j], matrix[~j][i], matrix[i][j], matrix[j][~i]
        return matrix

does what you are looking for.


However, I would use numpy , as it has a built in method for rotating matrices:

import numpy as np
mat = np.array([['a','b'],
         ['c','d']])

def rotate_matrix(matrix):
    return np.rot90(matrix, 3) // * SEE NOTE

print(rotate_matrix(mat))

Returns:

[['c' 'a']
 ['d' 'b']]


NOTE: the rot90 method offers counterclockwise rotation. Since you request clockwise rotation, you must specify an argument of 3 to specify the amount of counterclockwise rotations that should be made to achieve a clockwise rotation.

this is the solution of your problem, you have to use the assignment value proper

try to see the assignment you are doing,

in term of index : (0,0) --> (0,1) , (0,1) --> (1,1), (1,0) -->(0,0) and (1,1) --> (1,0) this is wrong .

that is why you are getting the wrong solution

what you should do was match index as

(0,0) -->(0,1) , (0,1)-->(0,0) , (1,1)-->(0,1),(1,0)-->(1,1)

below is the correct solution.

def rotate_matrix(matrix):
        for i in range(len(matrix)//2):
            for j in range(i, len(matrix)-i-1):
               matrix[i][j], matrix[~i][j], matrix[i][~j], matrix[~i][~j]= matrix[~i][j],matrix[i][~j],matrix[i][j],matrix[~i][~j]
        return matrix

a = [
 ['a','b'],
 ['c', 'd']
]

print(rotate_matrix(a))
# output [['c', 'a'], ['b', 'd']]

this is the solution of the problem you are trying to solve, ie rotation of a matrix at 90 degree # Python program to rotate a matrix

# Function to rotate a matrix 
def rotateMatrix(mat): 

    if not len(mat): 
        return

    """ 
        top : starting row index 
        bottom : ending row index 
        left : starting column index 
        right : ending column index 
    """

    top = 0
    bottom = len(mat)-1

    left = 0
    right = len(mat[0])-1

    while left < right and top < bottom: 

        # Store the first element of next row, 
        # this element will replace first element of 
        # current row 
        prev = mat[top+1][left] 

        # Move elements of top row one step right 
        for i in range(left, right+1): 
            curr = mat[top][i] 
            mat[top][i] = prev 
            prev = curr 

        top += 1

        # Move elements of rightmost column one step downwards 
        for i in range(top, bottom+1): 
            curr = mat[i][right] 
            mat[i][right] = prev 
            prev = curr 

        right -= 1

        # Move elements of bottom row one step left 
        for i in range(right, left-1, -1): 
            curr = mat[bottom][i] 
            mat[bottom][i] = prev 
            prev = curr 

        bottom -= 1

        # Move elements of leftmost column one step upwards 
        for i in range(bottom, top-1, -1): 
            curr = mat[i][left] 
            mat[i][left] = prev 
            prev = curr 

        left += 1

    return mat 

# Utility Function 
def printMatrix(mat): 
    for row in mat: 
        print row 


# Test case 1 
matrix = [
 ['a','b'],
 ['c', 'd']
]



matrix = rotateMatrix(matrix) 
# Print modified matrix 
printMatrix(matrix) 

# output [['c', 'a'], ['b', 'd']]

ps second solution coping from geeksforgeets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM