旋转一个正方形

问题描述

所以我要构建的是一个程序,它需要一个 3x3 的正方形并根据指令旋转它。例如,如果我有 3x3 正方形

0 5 2   
7 8 4   
1 6 3 

旋转是这些

U 2
D 2
L 1
D 2

然后我旋转它:在第二列上

0   5   4   
7   8   3   
1   6   2

二楼

0   5   2   
7   8   4   
1   6   3 

在第一行左边 - 不确定是不是右边

0   5   2   
8   4   7   
1   6   3 

在第二行下方

0 5 3
8 4 2
1 6 7

最终轮换应该是

0 5 3
8 4 2
1 6 7

下面是我的程序,我设法运行了文件生成一个 3x3,但我不知道如何移动正方形,如果有人可以通过提供有关我如何开始移动的指针来帮助这一点,非常感谢。

def readfile(x):
    list=[]
    file= open(x)
    count=0
    maxcount=0
    while True:
        line = file.readline()
        if count<3:
            line=line.rstrip('\n').split(' ')
            x=[]
            for i in line:
                x.append(int(i))
            list.append(x)
            count+=1
        elif count==3:
            maxcount=int(line.rstrip('\n'))
            for i in range(count):
                for j in range(count):
                    print(list[i][j],' ',end=' ')
                print()
            print(maxcount)
            count+=1
        elif maxcount>0:
            line=line.rstrip('\n')
            lines=line.split(' ')
            print(" ".join(lines))
            maxcount-=1
readfile("file.txt")

解决方法

我已经定义了两个执行这些操作的函数。你可以传递 right=True 或 up=True 并且有一个可选参数,通过它旋转 n 步。

def rotate_row_elements(matrix,row,by,right=True):
    if right:
        for i in range(by):
            matrix[row] = [matrix[row].pop(),*matrix[row]]
    else:
        for i in range(by):
            matrix[row] = [*matrix[row][1:],matrix[row][0]]

def rotate_col_elements(matrix,col,down=True):
    if down:
        temp = [matrix[j][col] for j in range(len(matrix))]
        
        for i in range(by):
            temp = [temp.pop(),*temp]
            
        for j in range(len(matrix)):
            matrix[j][col] = temp[j]
            
    else:
        
        temp = [matrix[j][col] for j in range(len(matrix))]
        for i in range(by):
            temp = temp[1:] + [temp[0]]
        
        for j in range(len(matrix)):
            matrix[j][col] = temp[j]        


matrix = [
    
[0,5,2],[7,8,4  ],[1,6,3 ]]
rotate_col_elements(matrix,1,2)
print(matrix)

[[0,4],3]]