Last active
November 17, 2017 18:30
-
-
Save SteadBytes/3d511e46dd1e9fcdeba1531eb7311061 to your computer and use it in GitHub Desktop.
Timing comparisons for recursive and iterative factorial functions
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
import timeit | |
# Add a memoization method? | |
def factorial(n): | |
if n == 0: | |
return 1 | |
else: | |
return n * factorial(n - 1) | |
def factorial_iterative(n): | |
product = 1 | |
for i in range(1, n + 1): | |
product *= i | |
return product | |
if __name__ == '__main__': | |
print('factorial():') | |
print(timeit.timeit('factorial(15)', number=10000, | |
setup='from __main__ import factorial')) | |
print('factorial_iterative():') | |
print(timeit.timeit('factorial_iterative(15)', number=10000, | |
setup='from __main__ import factorial_iterative')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment