以下是一个按顺时针顺序打印数字金字塔的示例代码:
def print_pyramid(n):
# 创建一个 n x n 的二维数组
pyramid = [[0] * n for _ in range(n)]
# 定义四个方向的边界
top = 0
bottom = n - 1
left = 0
right = n - 1
# 定义当前要填充的数字
num = 1
while top <= bottom and left <= right:
# 从左到右打印上边界
for i in range(left, right + 1):
pyramid[top][i] = num
num += 1
top += 1
# 从上到下打印右边界
for i in range(top, bottom + 1):
pyramid[i][right] = num
num += 1
right -= 1
# 从右到左打印下边界
for i in range(right, left - 1, -1):
pyramid[bottom][i] = num
num += 1
bottom -= 1
# 从下到上打印左边界
for i in range(bottom, top - 1, -1):
pyramid[i][left] = num
num += 1
left += 1
# 打印金字塔
for row in pyramid:
for num in row:
print(num, end=' ')
print()
# 调用函数打印一个5层的数字金字塔
print_pyramid(5)
输出结果为:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
这段代码使用一个二维数组来表示金字塔,然后按照顺时针的顺序依次填充数字。具体的逻辑是从外层开始,先按顺时针方向填充上边界,然后再填充右边界,接着填充下边界,最后填充左边界。每填充一条边界后,更新对应的边界位置。最后打印出整个金字塔的结果。
上一篇:按顺时针方向排序点
下一篇:按顺时针顺序排序多维点