Skip to content

Instantly share code, notes, and snippets.

@vergenzt
Created August 8, 2012 20:28
Show Gist options
  • Save vergenzt/3298357 to your computer and use it in GitHub Desktop.
Save vergenzt/3298357 to your computer and use it in GitHub Desktop.
Write a number spiral
from spiral import write_spiral
write_spiral(7)
# Prints:
# 37 36 35 34 33 32 31
# 38 17 16 15 14 13 30
# 39 18 5 4 3 12 29
# 40 19 6 1 2 11 28
# 41 20 7 8 9 10 27
# 42 21 22 23 24 25 26
# 43 44 45 46 47 48 49
write_spiral(6)
# Prints:
# 26 25 24 23 22 21
# 27 10 9 8 7 20
# 28 11 2 1 6 19
# 29 12 3 4 5 18
# 30 13 14 15 16 17
# 31 32 33 34 35 36
def write_row(n, row):
def tl_corner(n): return (n-1)**2 + 1
def tr_corner(n): return tl_corner(n) - (n-1)
def br_corner(n): return n**2
def bl_corner(n): return br_corner(n) - (n-1)
if row == 0:
for i in range(tl_corner(n), tr_corner(n)-1, -1):
write(i)
elif row == n-1:
for i in range(bl_corner(n), br_corner(n)+1):
write(i)
else:
write(tl_corner(n) + row)
write_row(n-2, row-1)
write(tr_corner(n) - row)
def write_spiral(n):
for i in range(n):
write_row(n, i)
print
def write(n):
print " %2d" % n,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment