Created
October 30, 2013 21:42
-
-
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.
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
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