我试图在
python中顺时针旋转一个3 * 3矩阵90度.
我已经确定[i] [j]处的元素转到[j] [new_i].
这里new_i取决于之前的i,所以我为它做了一个叫做圆减法的函数.
如果我是0则new_i是2
如果我是1那么new_i是1
如果我是2那么new_i是0
执行后,它给了我意想不到的结果.
我已经打印了每次迭代中发生的所有事情.
我无法弄清楚一些元素如何被不同的元素取代.
'''
1 2 3 7 4 1
4 5 6 rotate 90 degrees 8 5 2
7 8 9 9 6 3
'''
def circular_subtraction(i):
new_i = i
if(i==0):
new_i = 2
elif(i==1):
new_i = 1
elif(i==2):
new_i = 0
return new_i
def rotate_clock(matrix):
new_matrix = matrix
for i in range(len(matrix)):
for j in range(len(matrix)):
new_i = circular_subtraction(i)
new_matrix[j][new_i] = matrix[i][j]
print("New element added from {},{} to {},{} ::: {} to {}".format(i+1,j+1,j+1,new_i+1,matrix[i][j],new_matrix[j][new_i]))
for each_row in new_matrix:
print(each_row)
matrix = [[1,2,3],[4,5,6],[7,8,9]]
print("Length of the matrix : ",len(matrix))
for each_row in matrix:
print(each_row)
print()
matrix = rotate_clock(matrix)
输入矩阵是
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
预期结果是:
[7, 4, 1]
[8, 5, 2]
[9, 6, 3]
结果是:
[7, 4, 1]
[2, 5, 2]
[1, 2, 1]