Advertisement
Guest User

Other Doug's Spiral #1

a guest
Sep 25th, 2010
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import sys
  2.  
  3. init_table = lambda ncols, nrows: [ [ None ] * ncols for i in xrange(nrows) ]
  4.  
  5. def iter_spiral(ncols, nrows):
  6.  
  7.     row, col = 0, 0
  8.  
  9.     # RED_FLAG: this is a HACK so that enumerate can be used as the
  10.     #           counter and so we can skip the initial '0' value.
  11.     #           Bad Doug! (not Hellman... the other one)
  12.     yield row, col
  13.  
  14.     rowstart, rowstop = 0, nrows
  15.     colstart, colstop = 0, ncols
  16.  
  17.     while rowstart < rowstop and colstart < colstop:
  18.         for col in xrange(colstart, colstop):
  19.             yield row, col
  20.  
  21.         rowstart += 1
  22.         for row in xrange(rowstart, rowstop):
  23.             yield row, col
  24.  
  25.         colstop -= 1
  26.         for col in xrange(colstop-1, colstart-1, -1):
  27.             yield row, col
  28.  
  29.         rowstop -= 1
  30.         for row in xrange(rowstop-1, rowstart-1, -1):
  31.             yield row, col
  32.  
  33.         colstart += 1
  34.  
  35.  
  36. def spiral(ncols, nrows):
  37.  
  38.     ## Initialize an empty table
  39.     table = init_table(ncols, nrows)
  40.  
  41.     ## Fill it in with values
  42.     for val, (row, col) in enumerate(iter_spiral(ncols, nrows)):
  43.         table[row][col] = val
  44.  
  45.     ## Print it out
  46.     for row in table:
  47.         for cell in row:
  48.             print "%4d" % cell,
  49.         print
  50.  
  51.  
  52. spiral(*[int(v) for v in sys.argv[1:3]])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement