|
|
|
|
|
by eipi
5208 days ago
|
|
Memoized version: class Factorial(object):
def __init__(self):
self.n = 0
self.fact_n = 1
def next_fact(self):
self.fact_n *= (self.n + 1)
self.n += 1
def prev_fact(self):
self.fact_n /= self.n
self.n -= 1
def fact(self, n):
if n == self.n:
return self.fact_n
elif n > self.n:
# start from self.n working forward
self.next_fact()
return self.fact(n)
else:
# start from fact_n working backwards
self.prev_fact()
return self.fact(n)
fobj = Factorial()
print fobj.fact(6)
print fobj.fact(8)
print fobj.fact(3)
|
|