Understanding factorial function in python

I am trying to figure out if there is the following Python function:

def factorial(i):
    if not hasattr(factorial, 'lstFactorial'):
        factorial.lstFactorial = [None] * 1000
    if factorial.lstFactorial[i] is None:
        iProduct = 1
        for iFactor in xrange(1, i+1):
            iProduct *= iFactor
        factorial.lstFactorial[i] = iProduct
    return factorial.lstFactorial[i]

will give the same results as the equivalent in C #:

long factorial(long n) 
{ 
   return n <= 1 ? 1 : n * factorial(n-1);
}

for a value of 12 or less.

I don't know anything about Python, but just converted Python code to C #. This was the only function that I did not quite understand.

+3
source share
6 answers

here is the main algorithm

iProduct = 1
for iFactor in xrange(1, i+1):
    iProduct *= iFactor

another code is for caching results.

+4
source

Python, , . # , Python ( , memoization/caching - , ).

, - , .

+2

IANAPG (Python Guru), , 1000 , , . ++ - :

long factorial(int i){
    //Cache array
    static long factorials[1000];
    if (!factorials[i]){ //If not cached, calculate & store
        int product = 1;
        for (int idx = 1; idx <= i + 1; ++idx){
            product *= idx;
        }
        factorials[i] = product;
    }
    return factorials[i]; //Return cached value
}
+2

, Python, , ,

+1

lstFactorial to factorial. 1000 , .

+1
source
def factorial(i):
    if not hasattr(factorial, 'lstFactorial'): #program checks whether caching list exists
        factorial.lstFactorial = [None] * 1000 #if so, it creates a list of thousand None elements (it is more or less equivalent to C/C++ NULL
    if factorial.lstFactorial[i] is None: #prog checks if that factorial has been already calculated
        iProduct = 1 #set result to 1
        for iFactor in xrange(1, i+1): # C for(iFactor = 1; iFactor &lt;= i+1; iFactor++)
            iProduct *= iFactor #we multiply result times current loop counter
        factorial.lstFactorial[i] = iProduct #and put result in caching list
    return factorial.lstFactorial[i] #after all, we return the result, calculated jest now or obtained from cache

Honestly, this is not the best algorithm, since it uses the cache only partially.

Simple, user-friendly factorial function (no caching):

def factorial(i):
    if i == 0 or i == 1:
        return 1
    return i*factorial(i-1)

For lazy python programmers most similar to C # example:

f = lambda i: i and i*f(i-1) or 1
+1
source

Source: https://habr.com/ru/post/1721339/


All Articles