How do I make make spiral in python?

Skizo picture Skizo · May 17, 2014 · Viewed 19.6k times · Source

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:
enter image description here
I tried different ways but nothing worked out. I just cant figure it out.
Hope I explained myself properly.

Answer

roippi picture roippi · May 17, 2014

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