Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Created March 11, 2012 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghoseb/2015126 to your computer and use it in GitHub Desktop.
Save ghoseb/2015126 to your computer and use it in GitHub Desktop.
Some factorial implementations in Python
import operator
# naive recursive solution
def fact1(n):
if n <= 1:
return 1
return n * fact1(n - 1)
fact2 = lambda n: reduce(operator.mul, xrange(1, n + 1))
# for loop solution
def fact3(n):
res = 1
for i in range(1, n+1):
res = res * i
return res
# same as fact2, but uses a lambda instead of operator.mul
# fact4 = lambda n: reduce(lambda x, y: x * y, xrange(1, n + 1))
# same as fact1, but uses an accumulator for possible TCO
def fact5(n):
def fact(n, acc):
if n<= 1:
return acc
return fact(n - 1, n * acc)
return fact(n, 1)
if __name__ == '__main__':
from timeit import timeit
print "Naive recursive solution => ",
print timeit(lambda: fact1(100))
print "Reduce solution => ",
print timeit(lambda: fact2(100))
print "For loop solution => ",
print timeit(lambda: fact3(100))
print "Tail recursive solution => ",
print timeit(lambda: fact5(100))
# PyPy
# Naive recursive solution => 28.4803950787
# Reduce solution => 13.8635640144
# For loop solution => 13.879529953
# Tail recursive solution => 32.0280330181
# CPython
# Naive recursive solution => 47.6345591545
# Reduce solution => 22.992249012
# For loop solution => 24.9572100639
# Tail recursive solution => 60.3095831871
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment