Python旋转魔方阵

【问题描述】
输入一个自然数N(2≤N≤9),要求输出如下的魔方阵,即边长为N*N,元素取值为1至N*N,1在左上角,呈顺时针方向依次放置各元素。
 N=3时:
    1    2    3
    8    9    4
    7    6    5
【输入形式】
从标准输入读取一个整数N。
【输出形式】
向标准输出打印结果。输出符合要求的方阵,每个数字占5个字符宽度,向右对齐,在每一行末均输出一个回车符。
【输入样例】

4

【输出样例】

    1    2    3    4
   12   13   14    5
   11   16   15    6
   10    9    8    7

 1 Dir_tuple = ('', '', '', '')
 2 def dir_changer(counter, direction, lap_len):#创建转向函数
 3     if counter == lap_len:#从右转向下
 4         return ('',0)
 5     elif counter == (lap_len*2)-1:#从下转向左
 6         return ('',0)
 7     elif counter == (lap_len*3)-2:#从左转向上
 8         return ('',0)
 9     elif counter == (lap_len*4)-4:#从上转向右
10         return ('',1)#返回缩小待填充矩阵的参数
11     else:
12         return (direction,0)#不作转向处理
13 
14     
15 def mof(n):
16     alist = []#创建空列表
17     blist = [0] * n
18     for i in range(n): 
19         alist.append(blist[:])#创建矩阵
20     counter = 0#初始化计数器
21     lap_len = n#初始化边长
22     direction = ''#初始化方向
23     x = y = 0#初始化坐标
24     
25     for i in range(1,pow(n,2)+1):#将1到n**2填充至矩阵中
26         alist[y][x] = i#填充
27         counter += 1#计数器增加
28         direction, lap_change= dir_changer(counter, direction, lap_len)#调用转向函数
29         if lap_change == 1:#缩小待填充矩阵
30             lap_len -= 2
31             counter = 0#重置计数器
32         if direction == '':#转向
33             x += 1
34         elif direction == '':
35             y += 1
36         elif direction == '':
37             x -= 1
38         elif direction == '':
39             y -= 1
40     return alist#返回矩阵
41 
42 N = int(input())
43 res_list = mof(N)
44 for i in res_list:#打印
45     for j in i:
46         print("{:5}".format(j),end='')
47     print()

 

posted @ 2021-12-08 17:47  newIDK  阅读(671)  评论(0)    收藏  举报