In python, which function one runs faster? def f(n): ans = a = 1 while a <= n: ans *= a a += 1 return ans or f = lambda n: reduce(lambda x,y: x*y, xrange(1, n+1)) if n > 1 else 1 or from math import factorial as f
or uses less memory
Personally if I find a library (especially standard library) function that someone else wrote, I would use that over anything I've written. Even better if I can take that library function and modify it myself to work better!
I think theres a timeit library function in Python that will let me know which function is best
Empirical data is interesting, but inconclusive. If you really need something safe, you should learn how factorial at the math module works, as it is likely better code than me and you could write at the moment, but built-ins (or predefined functions) might include some overhead, as they have to generalize more than you need, making them a bit slower in some cases (that might not be this case). An easy example is: you can reduce a lot of type checking if the function doesn't interact directly with the user. As math is implemented as a .pyd file, I had to search for the actual source code, and I think it's this one : http://svn.python.org/view/python/trunk/Modules/mathmodule.c?view=markup That being said, if you really one a faster factorial, consider cacheing(?) the computed values, as this implementation : http://code.activestate.com/recipes/577241-faster-factorial/
I'd generally go for library functions unless performance becomes critical. Library functions are often tuned by others for speed, so you don't need to worry about it, and when you do, you know what your bottleneck is.
Join our real-time social learning platform and learn together with your friends!