如何在python中制作螺旋状螺旋形? [英] How do I make make spiral in python?

查看:271
本文介绍了如何在python中制作螺旋状螺旋形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个给它一个数字的函数,并且该函数返回从1到该数字的螺旋形(在二维数组中).例如,如果将数字25赋予函数,它将返回类似以下内容的内容:

我尝试了不同的方法,但没有解决.我只是想不通.
希望我能正确地解释自己.

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:

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:

  • (方向)向右移动,然后向下移动,然后向左移动,然后向上移动,然后...(希望这很明显)
  • (幅值)先移动一次,然后移动一,然后移动两个,然后移动两个,然后移动三个...

因此,使用这些规则,编写一个生成number, coordinates元组的生成器.

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

演示:

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))]

这篇关于如何在python中制作螺旋状螺旋形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆