Sie können auf einem separaten Modul, utils.py, einige hausgemachte faktorielles Funktionen speichern und dann importiere sie und vergleiche die Performance mit der vordefinierten, in scipy, numpy und math mit timeit. In diesem Fall habe ich als externe Methode verwendet, die von Stefan Gruenwald vorgeschlagen zuletzt:
import numpy as np
def factorial(n):
return reduce((lambda x,y: x*y),range(1,n+1))
Hauptcode (ich einen Rahmen von JoshAdel in einem anderen Beitrag vorgeschlagen verwendet, suchen Sie nach wie-can-i-get-an-Array -von-Wechsel Werte-in-python):
from timeit import Timer
from utils import factorial
import scipy
n = 100
# test the time for the factorial function obtained in different ways:
if __name__ == '__main__':
setupstr="""
import scipy, numpy, math
from utils import factorial
n = 100
"""
method1="""
factorial(n)
"""
method2="""
scipy.math.factorial(n) # same algo as numpy.math.factorial, math.factorial
"""
nl = 1000
t1 = Timer(method1, setupstr).timeit(nl)
t2 = Timer(method2, setupstr).timeit(nl)
print 'method1', t1
print 'method2', t2
print factorial(n)
print scipy.math.factorial(n)
dem es heißt:
method1 0.0195569992065
method2 0.00638914108276
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Process finished with exit code 0
Das gute an 'scipy.misc.factorial' ist, dass es nur ein einziges Mal die Fakultät berechnet - für von die größte Zahl r im Array. Alle anderen werden dabei als Nebeneffekt berechnet. –
Verfallswarnung: in scipy 1.0.0. Verwende 'scipy.special.factorial' – lincolnfrias