Source

puzzles / spiral.py

Full commit
#!/usr/bin/env python
"""Fill in an Oblong number spiral.

http://codegolf.com/oblongular-number-spirals
"""

import itertools
import sys

if len(sys.argv) != 3:
    print 'Usage: %s <num_cols> <num_rows>' % sys.argv[0]
    sys.exit(1)
num_cols = int(sys.argv[1])
num_rows = int(sys.argv[2])

rows = range(num_rows)
cols = range(num_cols)

# Initialize the array
spiral = [ [0] * num_cols for row in xrange(num_rows) ]

# Establish a counter
n = itertools.count(1)

while rows or cols:
    
    # Row left to right
    if rows:
        r = rows.pop(0)
        for c in cols:
            spiral[r][c] = n.next()

    # Column top to bottom
    if cols:
        c = cols.pop(-1)
        for r in rows:
            spiral[r][c] = n.next()
    
    # Row right to left
    if rows:
        r = rows.pop(-1)
        for c in reversed(cols):
            spiral[r][c] = n.next()

    # Column bottom to top
    if cols:
        c = cols.pop(0)
        for r in reversed(rows):
            spiral[r][c] = n.next()

# Show the results
for r in xrange(num_rows):
    for c in xrange(num_cols):
        print '%3d' % spiral[r][c],
    print