我的任务是在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.
注意事项:
-
和一个\
-
,以\
开头,以/
结尾例如,当
n
为4时:第一行:
- - - \
最后一行:
\ - - /
可通过以下方式轻松实现:
现在,关于螺旋体,请注意以下事项:
n=3时:
^{pr2}$n=5时:
n=6时:
请注意,4-螺旋线包含在其中内,红色方框固定。只有它们的长度根据n变化。在
它就在里面。而在n=7之前,n=5包含在其中。同样,对于n=2k,每个n都包含n/2螺旋线。在
我想说的是,你手动画出n=3和n=2。如果螺旋线应该由一个偶数组成,那么可以使用n=2模式,构造第一行和最后一行,使用循环可以附加螺旋体的主体。在
例如n=5:
其中
spiral
是大小为3的初始螺旋:为了生成7螺旋,您需要:
你会得到:
当然,这是可以改进的,你可以使程序更有效,我只想给你一个指导,并分享我的想法。。在
以下是更多有趣的螺旋:
您还可以免费获得金字塔的俯视图
由于已经有了一些很好的解决方法,我按照我喜欢的方式做了代码,它以螺旋式的顺序运行,并在一路上设置了字符。它有点长,但为了便于理解,可以缩短大约一半:
我尊重你不想要完整的代码。这只是有意的部分回答。在
首先制作一个二维数组。比如:
这允许您编写类似
grid[i][j] = '\'
的代码。在从
i,j = 0,0
开始。绕着网格旋转。将接受值direction
的变量'right', 'left', 'up', 'down'
与相应的delta
一起添加到(i,j)
以实现移动。在沿着一条线沿着某个方向放置“-”或“|”,直到碰到一个角(检查
None
以及整个网格的限制)。当你到了一个角落,放置适当的角落标记和改变方向。在填充网格后,用空字符串分隔符连接每一行,并用
'\n'
作为分隔符连接结果。在相关问题 更多 >
编程相关推荐