Michael
Michael

Reputation: 11

spiral pattern python

I was wondering how to print the following pattern for a given number "m" in python. My idea was to use a string to create each line separately. but I cannot deploy the output. it gives me sth different and I think I am thinking and solving a wrong way.

Clarification: this is an extended version of a problem appeared in a local programming contest in 2019 in Nepal and not a homework or something similar. the original problem was asking to find the coordinate of final point

Upvotes: 1

Views: 501

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54668

You can do it by actually simulating the snail's path. I suspect this is easier than reverse-engineering the final pattern row by row. Pass the N value on the command line. This version starts from the inside and works out, which it turns out is easier.

import sys

N = int(sys.argv[1])

grid = [[' ']*N for _ in range(N+2)]

# Where is the center?
x = y = N // 2
if N % 4 == 3:
    x -= 1
grid[y][x] = '+'
dir = (1,0)
incr = 2

def printgrid(grid):
    for row in grid:
        print(' '.join(row))

def draw(grid,x,y,n,dir):
    for i in range(n):
        x += dir[0]
        y += dir[1]
        grid[y][x] = '-'
    grid[y][x] = '+'
    return x,y

while x+dir[0]*incr in range(N) and y+dir[1]*incr in range(N):
    x, y = draw( grid, x, y, incr, dir )
    dir = (-dir[1],dir[0])

    x, y = draw( grid, x, y, incr, dir )
    dir = (-dir[1],dir[0])
    
    incr += 2

draw( grid, x, y, incr-2, dir )
printgrid(grid)

Output:

timr@tims-gram:~/src$ python x.py 17
+ - - - - - - - - - - - - - - - +
-                                
-   + - - - - - - - - - - - - - +
-   -                           -
-   -   + - - - - - - - - - +   -
-   -   -                   -   -
-   -   -   + - - - - - +   -   -
-   -   -   -           -   -   -
-   -   -   -   + - +   -   -   -
-   -   -   -       -   -   -   -
-   -   -   + - - - +   -   -   -
-   -   -               -   -   -
-   -   + - - - - - - - +   -   -
-   -                       -   -
-   + - - - - - - - - - - - +   -
-                               -
+ - - - - - - - - - - - - - - - +
                                                                  

Upvotes: 3

Related Questions