Last active
December 25, 2015 18:59
-
-
Save wrenoud/7024996 to your computer and use it in GitHub Desktop.
Pointless recursion.
This file contains hidden or 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 countTo10_recursively(count = 0): | |
if(count <= 10): | |
countTo10_recursively(count + 1) | |
# which is the same as | |
def countTo10_theObviousWay(): | |
for count in xrange(10): | |
pass | |
# lets do some tests | |
if __name__ == "__main__": | |
from timeit import timeit | |
t1 = timeit("countTo10_recursively()", \ | |
setup="from __main__ import countTo10_recursively", \ | |
number=10000) | |
t2 = timeit("countTo10_theObviousWay()", \ | |
setup="from __main__ import countTo10_theObviousWay", \ | |
number=10000) | |
print t1, t2 |
The results get worse for the recursive approach as you increase the number it's counting to. It looks like the stack has a limit of 1000, and I think the slow down is due to the overhead of maintaining the stack for each recursive call.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On my computer the for loop is 4 times faster than the recursive approach.