一个小练习题,输出如下规律的数字矩阵,从一开始先向下,再向右,再向上,最后向左,依次类推,绕圈圈输出。
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09
#获取下一个方向
def getNextFlag(flag):
if flag == 0:
return 1
elif flag == 1:
return 2
elif flag == 2:
return 3
elif flag == 3:
return 0
else:
return 4
#生成矩阵
def matrix():
length = input("Please enter the length of the two-dimensional table :")
num = int(length)
#创建一个二维表
array = []
for i in range(num):
array.append([0] * num)
#判断数字格式
format_num = "%0" + str(len(str(num*num))) + "d"
#0向下 1向右 2向上 3向左
flag = 0
total = 1
column_index = 0
row_index = 0
border = num - 1
#开始赋值
array[row_index][column_index] = total
while total < num*num:
if flag == 0 and border > row_index >=0:
if array[row_index+1][column_index] == 0:
row_index += 1#移动
#赋值
total += 1
array[row_index][column_index] = total
else:
flag = getNextFlag(flag)
elif flag == 1 and border > column_index >=0:
if array[row_index][column_index+1] == 0:
column_index +=1
total += 1
array[row_index][column_index] = total
else:
flag = getNextFlag(flag)
elif flag == 2 and border >= row_index > 0:
if array[row_index-1][column_index] == 0:
row_index -= 1
total += 1
array[row_index][column_index] = total
else:
flag = getNextFlag(flag)
elif flag == 3 and border >= column_index > 0:
if array[row_index][column_index-1] == 0:
column_index -=1
total += 1
array[row_index][column_index] = total
else:
flag = getNextFlag(flag)
else:
flag = getNextFlag(flag)
#打印矩阵
for ele in array:
for element in ele:
print(format_num % element,end=" ")
print("")
#调用
matrix()