Answer to Question #330871 in Python for anu

Question #330871

matrix rotation


1
Expert's answer
2022-04-19T10:01:26-0400
def rotate_right(matrix):
    rotate = list(zip(*reversed(matrix)))
    return [list(element) for element in rotate]


def rotate_left(matrix):
    rotate = list(zip(*reversed(matrix)))
    return [list(element)[::-1] for element in rotate][::-1]


original = [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]]

for i in range(3):
    for j in range(3):
        print(original[i][j], end=' ')
    print()
while True:
    x = input("Enter 'L' or 'R' for rotate ('E' - exit): ")
    if x == 'L' or x == 'l':
        rotate_l = rotate_left(original)
        original = rotate_l
        for i in range(3):
            for j in range(3):
                print(rotate_l[i][j], end=' ')
            print()
    elif x == 'R' or x == 'r':
        rotate_r = rotate_right(original)
        original = rotate_r
        for i in range(3):
            for j in range(3):
                print(rotate_r[i][j], end=' ')
            print()
    elif x == 'E' or x == 'e':
        exit()
    else:
        print("You entered an invalid letter")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS