gpt4 book ai didi

python - 生成 NXN 螺旋线

转载 作者:太空狗 更新时间:2023-10-29 19:31:27 29 4
gpt4 key购买 nike

我的任务是在 python 中创建一个螺旋,用户输入一个数字,例如 3,它将输出一个 3x3 的螺旋,如下所示:

- - \
/ \ |
\ - /

我不是在寻找完整的代码我只是不知道该怎么做,显然使用 if 语句打印出所有可能的解决方案是不可能的或不合逻辑的。这里真正的问题是我应该做什么,对于循环,定义我自己的函数?是否有人可以将我链接到任何文档,这会有所帮助。完整任务大纲如下:

Your task here is to write a program to draw a spiral of a given size inside a box.

Your program should ask the user for a positive integer denoting the size of the box. Your program should then print out a spiral inside of a box of that size.

For example:

Enter size: 3
- - \
/ \ |
\ - /

and:

Enter size: 4
- - - \
/ - \ |
| \ / |
\ - - /

​and:

Enter size: 5     
- - - - \
/ - - \ |
| / \ | |
| \ - / |
\ - - - /

The input size will always be greater than 1.

最佳答案

我尊重你不想要完整的代码。这只是部分答案。

首先制作一个二维数组。像这样的东西:

grid = [[None]*n for i in range(n)]

这允许您编写类似 grid[i][j] = '\' 的代码。

i,j = 0,0 开始。在围绕网格的循环螺旋中。拥有一个变量 direction 可能会有所帮助,它具有值 'right', 'left', 'up', 'down' 以及相应的 delta 采用 (0,1) 之类的值(用于向右移动)添加到 (i,j) 以实现移动。

沿着特定方向的一条线放置'-'或'|'直到你碰到一个角落(检查 None 以及整个网格的限制)。当您到达拐角时,放置适当的拐角标记并改变方向。

填充网格后,使用空字符串分隔符连接每一行,并使用 '\n' 作为分隔符连接结果。

关于python - 生成 NXN 螺旋线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31832862/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com