RosettaCodeData/Task/Zig-zag-matrix/Python/zig-zag-matrix-2.py

34 lines
769 B
Python
Raw Permalink Normal View History

2019-09-12 10:33:56 -07:00
# pylint: disable=invalid-name
# pylint: disable=unused-argument
"ZigZag iterator."
import sys
if sys.version_info[0] >= 3:
xrange = range
def move(x, y, columns, rows):
"Tells us what to do next with x and y."
if y < (rows - 1):
return max(0, x-1), y+1
return x+1, y
def zigzag(rows, columns):
"ZigZag iterator, yields indices."
2013-04-11 01:07:29 -07:00
x, y = 0, 0
2019-09-12 10:33:56 -07:00
size = rows * columns
for _ in xrange(size):
yield y, x
2013-04-11 01:07:29 -07:00
if (x + y) & 1:
2019-09-12 10:33:56 -07:00
x, y = move(x, y, columns, rows)
2013-04-11 01:07:29 -07:00
else:
2019-09-12 10:33:56 -07:00
y, x = move(y, x, rows, columns)
# test code
i, rows, cols = 0, 5, 5
mat = [[0 for x in range(cols)] for y in range(rows)]
for (y, x) in zigzag(rows, cols):
mat[y][x], i = i, i + 1
2013-04-11 01:07:29 -07:00
from pprint import pprint
2019-09-12 10:33:56 -07:00
pprint(mat)