Skip to content

Instantly share code, notes, and snippets.

@ejhayes
Created March 4, 2011 21:11
Show Gist options
  • Select an option

  • Save ejhayes/855711 to your computer and use it in GitHub Desktop.

Select an option

Save ejhayes/855711 to your computer and use it in GitHub Desktop.
Generates the coordinates for a spiral!
"""
Displays the coordinates used to draw a circle.
Assumes top of the circle is (0,0)
- positive X = right
- positive y = down
To run on a spiral of width 3:
spiral.py -s 3
"""
from optparse import OptionParser
__version_info__ = ('1', '2', '3')
__version__ = '.'.join(__version_info__)
def spiral(width):
"""
Generate a spiral in a recursive fashion. Assumes that the top of the screen is (0,0)
"""
if( width < 1 ):
return None
elif( width == 1 ):
return (0,0)
else:
return spiral_r(width, 0)
def spiral_r(width, depth):
if( width == 2 ):
return [(depth, depth),(depth+1,depth),(depth+1,depth+1),(depth,depth+1)]
elif( width == 1 ):
# base case
return [(depth, depth)]
else:
# recursive case
buffer = []
for i in range(width):
# right width
buffer += [(i, depth) for i in range(depth, depth + width)]
# down width -1
buffer += [(depth + width - 1, depth + i) for i in range(depth + 1, depth + width)]
# left width -1
buffer += [(i, depth + width - 1) for i in range(depth+width-2,depth-1,-1)]
# up width - 2
buffer += [(depth,i) for i in range(depth+width-2,depth,-1)]
# append recursive answer
return buffer + spiral_r(width - 2, depth + 1)
if __name__ == '__main__':
# print out a test case
parser = OptionParser(version=__version__)
parser.add_option("-s","--size", dest="size",help="how wide should the spiral be? (default=3)", metavar="SIZE", type="int")
(options, args) = parser.parse_args()
if( type(options.size) != int ):
parser.error('Size must be an integer')
for i in spiral(options.size):
print i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment