Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Is math.factorial memoized?

I am solving a problem in three different ways, two are recursive and I memoize them myself. The other is not recursive but uses math.factorial. I need to know if I need to add explicit memoization to it.

Thanks.

like image 686
Paddy3118 Avatar asked Feb 12 '11 06:02

Paddy3118


2 Answers

Search for math_factorial on this link and you will find its implementation in python:

http://svn.python.org/view/python/trunk/Modules/mathmodule.c?view=markup

P.S. This is for python2.6

like image 60
Asterisk Avatar answered Sep 23 '22 20:09

Asterisk


Python's math.factorial is not memoized, it is a simple for loop multiplying the values from 1 to your arg. If you need memoization, you need to do it explicitly.

Here is a simple way to memoize using dictionary setdefault method.

import math
cache = {}
def myfact(x):
    return cache.setdefault(x,math.factorial(x))
print myfact(10000)
print myfact(10000)
like image 26
Senthil Kumaran Avatar answered Sep 25 '22 20:09

Senthil Kumaran