Last active
December 13, 2023 14:04
-
-
Save guilt/c421db704a84a1b79e423d96bd11bb0b to your computer and use it in GitHub Desktop.
ZigZag Iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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." | |
x, y = 0, 0 | |
size = rows * columns | |
for _ in xrange(size): | |
yield y, x | |
if (x + y) & 1: | |
x, y = move(x, y, columns, rows) | |
else: | |
y, x = move(y, x, rows, columns) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment