python怎么输出螺旋图案,我该如何在python中制作螺旋形?

I want to make a function that I give it a number and the function returns a spiral from 1 to that number(in 2 dimensional array). For example if I give the number 25 to the function it will return something like this:

98ec1fc28d8012d603061d3fefce8573.png

I tried different ways but nothing worked out. I just cant figure it out.

Hope I explained myself properly.

解决方案

Mostly the issue here is one of enumerating coordinates - match numbers to coordinates, then print it out however you want.

Start by noticing the two fundamental patterns:

(Direction) Move right, then down, then left, then up, then... (this is hopefully obvious)

(Magnitude) Move one, then one, then two, then two, then three...

So with those rules, write a generator that yields number, coordinates tuples.

It's clearest if you set up some helper functions first; I'll be extra verbose:

def move_right(x,y):

return x+1, y

def move_down(x,y):

return x,y-1

def move_left(x,y):

return x-1,y

def move_up(x,y):

return x,y+1

moves = [move_right, move_down, move_left, move_up]

Easy enough, now the generator:

def gen_points(end):

from itertools import cycle

_moves = cycle(moves)

n = 1

pos = 0,0

times_to_move = 1

yield n,pos

while True:

for _ in range(2):

move = next(_moves)

for _ in range(times_to_move):

if n >= end:

return

pos = move(*pos)

n+=1

yield n,pos

times_to_move+=1

demo:

list(gen_points(25))

Out[59]:

[(1, (0, 0)),

(2, (1, 0)),

(3, (1, -1)),

(4, (0, -1)),

(5, (-1, -1)),

(6, (-1, 0)),

(7, (-1, 1)),

(8, (0, 1)),

(9, (1, 1)),

(10, (2, 1)),

(11, (2, 0)),

(12, (2, -1)),

(13, (2, -2)),

(14, (1, -2)),

(15, (0, -2)),

(16, (-1, -2)),

(17, (-2, -2)),

(18, (-2, -1)),

(19, (-2, 0)),

(20, (-2, 1)),

(21, (-2, 2)),

(22, (-1, 2)),

(23, (0, 2)),

(24, (1, 2)),

(25, (2, 2))]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值