fork download
  1. from itertools import izip_longest, chain
  2.  
  3. rotate_cw = lambda arr: [list(row) for row in izip_longest(*arr[::-1])]
  4. rotate_ccw = lambda arr: [list(row) for row in izip_longest(*arr)][::-1]
  5.  
  6. def _print_spiral(arr, n):
  7. elem_template = '{{:>{}}}'.format(len(str(n*n)))
  8. row_template = ' '.join([elem_template] * n)
  9. spiral_template = '\n'.join([row_template] * n)
  10. print spiral_template.format(*chain(*arr))
  11.  
  12. def _gen_spiral(n, cw):
  13. arr, values = [[n*n]], range(n*n-1, 0, -1)
  14. rotate = rotate_cw if cw else rotate_ccw
  15. while values:
  16. m = len(arr[0])
  17. part, values = values[:m], values[m:]
  18. arr[-cw][1:] = part
  19. arr = rotate(arr)
  20. return rotate(arr) if cw else arr
  21.  
  22. def spiral(n, cw=True):
  23. arr = _gen_spiral(n, cw)
  24. _print_spiral(arr, n)
  25.  
  26. # Testing
  27. for n in (5, 4):
  28. for cw in (True, False):
  29. print '{} {}clockwise:'.format(n, 'counter-' * (not cw))
  30. spiral(n, cw)
  31. print
Success #stdin #stdout 0s 24080KB
stdin
Standard input is empty
stdout
5 clockwise:
 1  2  3  4  5
16 17 18 19  6
15 24 25 20  7
14 23 22 21  8
13 12 11 10  9

5 counter-clockwise:
 1 16 15 14 13
 2 17 24 23 12
 3 18 25 22 11
 4 19 20 21 10
 5  6  7  8  9

4 clockwise:
 1  2  3  4
12 13 14  5
11 16 15  6
10  9  8  7

4 counter-clockwise:
 1 12 11 10
 2 13 16  9
 3 14 15  8
 4  5  6  7