Last active
December 13, 2023 14:05
-
-
Save guilt/7deb8f44f15dee04ad622a424f401f63 to your computer and use it in GitHub Desktop.
Spiral 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 | |
"Spiral iterator." | |
import sys | |
if sys.version_info[0] >= 3: | |
xrange = range | |
def revrange(b, a=0, step=1): | |
"Reverse iterator." | |
return xrange(b-step, a-step, -step) | |
def spiral(rows, columns): | |
"Spiral iterator, yields indices." | |
if not columns or not rows: | |
return | |
# Go through the first row left to right. | |
for x in xrange(columns): | |
yield 0, x | |
# then last colum top to bottom. | |
for y in xrange(1, rows-1): | |
yield y, columns-1 | |
# then last row right to left (if not already visited). | |
if rows != 1: | |
for x in revrange(columns): | |
yield rows-1, x | |
# then first column bottom to top (if not already visited). | |
if columns != 1: | |
for y in revrange(rows-1, 1): | |
yield y, 0 | |
# then peel. | |
for y, x in spiral(rows-2, columns-2): | |
yield y+1, x+1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment