Sheng Zhou
2011-11-29 18:26:38+00:00

Have been asked to do a python exercise of printing a spiral numbers, like this:

1    2    3    4   5
18  19  20  21   6
17  28  29  22   7
16  27  30  23   8
15  26  25  24   9
14  13  12  11 10

Looks interesting, draft the code quickly maybe not very much optimized, but works:

```class Spiral:
def __init__(self):
pass

def run(self, w, h):
self.__construct_matrix(w,h)
self.__print_matrix()

def __construct_matrix(self, w, h):
self.matrix = []
for i in range(0,h): self.matrix.append([0]*w)
wlist  = range(0,h)
orient = -1
cnbr  = 1
while wlist:
orient = (orient + 1)%4
if orient == 0: # east
row = self.matrix[wlist.pop(0)]
for i, e in enumerate(row):
if e == 0:
row[i] = cnbr
cnbr += 1
elif orient == 1:
for rn in wlist:
for i in range(w-1, -1, -1):
if self.matrix[rn][i] == 0:
self.matrix[rn][i] = cnbr
cnbr += 1
break
elif orient == 2:
row = self.matrix[wlist.pop()]
for i in range(w-1, -1, -1):
if row[i] == 0:
row[i] = cnbr
cnbr += 1
elif orient == 3:
for rn in wlist[::-1]:
row = self.matrix[rn]
for i in range(0, w):
if row[i] == 0:
row[i] = cnbr
cnbr  += 1
break

def __print_matrix(self):
for row in self.matrix:
for e in row:
print "%3d"% e ,
print "\n"

if __name__ == '__main__':
Spiral().run(8, 10) # example: width 8, height 10

```
Spiral numbers
11-29 18:26 Sheng 1946chars 836visitors