Skip to content

Instantly share code, notes, and snippets.

@sjswitzer
Created October 30, 2013 21:42
Show Gist options
  • Save sjswitzer/7240844 to your computer and use it in GitHub Desktop.
Save sjswitzer/7240844 to your computer and use it in GitHub Desktop.
Python generators can't recurse in the conventional sense, but they can do something almost as good: recursively iterate other generators. Here's a classic recursion problem implemented as a generator.
def hanoiGenerator(n, a="left", b="center", c="right"):
if n > 0:
for i in hanoiGenerator(n-1, a, c, b):
yield i
yield (a, c)
for i in hanoiGenerator(n-1, b, a, c):
yield i
def test_hanoiGenerator():
for (fm, to) in hanoiGenerator(3):
print "Move", fm, "to", to
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment