Function for Factorial in Python

How do I calculate factorial of an integer in Python?

+115
python
Feb 27 2018-11-22T00:
source share
19 answers

The easiest way: math.factorial (x) (available in 2.6 and above).

If you want / must write it yourself, use something like

def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1)) 

or something more readable:

 def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) 

As always, Google is your friend;)

+168
Feb 27 2018-11-28T00:
source share

In Python 2.6 and later, try:

 import math math.factorial(n) 
+109
Feb 27 2018-11-27T00:
source share

Not necessarily, as it is such an old thread. But I did here another way to calculate the factorial of an integer using a while loop.

 def factorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num 
+23
Nov 01 '12 at 23:23
source share

Existing solution

The shortest and probably the fastest solution:

 from math import factorial print factorial(1000) 

Building your own

You can also create your own solution. Typically, you have two approaches. The one that suits me best:

 from itertools import imap def factorial(x): return reduce(long.__mul__, imap(long, xrange(1, x + 1))) print factorial(1000) 

(it also works for large numbers when the result becomes long )

The second way to achieve this:

 def factorial(x): result = 1 for i in xrange(2, x + 1): result *= i return result print factorial(1000) 
+19
Jan 29 2018-12-12T00:
source share
 def factorial(n): if n < 2: return 1 return n * factorial(n - 1) 
+7
Oct 19 '13 at 11:51 on
source share

If you are using Python2.5 or later, try

 from operator import mul def factorial(n): return reduce(mul, range(1,n+1)) 

for the new Python, there is a factorial in the math module, as stated in other answers here.

+6
Feb 27 2018-11-28T00:
source share

Another method for calculating factorial using a for-loop is

 def factorial(n): base = 1 for i in range(n,0,-1): base = base * i print base 
+4
Jul 25 '13 at 1:15
source share

Do you mean:

 def fact(n): f = 1 for i in range(1, n +1): f *= i return f 
+3
Feb 27 2018-11-27T00:
source share
+3
Feb 27 2018-11-28T00:
source share

For performance reasons, please do not use recursion. That would be disastrous.

 def fact(n, total=1): while True: if n == 1: return total n, total = n - 1, total * n 

Check running results

 cProfile.run('fact(126000)') 



 4 function calls in 5.164 seconds 

Using the stack is convenient (for example, a recursive call), but it is expensive: storing detailed information can take up a lot of memory.

If the stack is high, it means that the computer stores a lot of information about function calls.

The method takes up only read-only memory (as an iteration).

Or use for loop

 def fact(n): result = 1 for i in range(2, n + 1): result *= i return result 

Check running results

 cProfile.run('fact(126000)') 



 4 function calls in 4.708 seconds 



Or using the built-in math function

 def fact(n): return math.factorial(n) 

Check running results

 cProfile.run('fact(126000)') 



 5 function calls in 0.272 seconds 
+3
Mar 29 '18 at 9:50
source share

Here is my attempt

 >>> import math >>> def factorial_verbose(number): ... for i in range(number): ... yield f'{i + 1} x ' ... >>> res = ''.join([x for x in factorial_verbose(5)]) >>> res = ' '.join([res[:len(res)-3], '=', str(math.factorial(5))]) >>> res '1 x 2 x 3 x 4 x 5 = 120' 
+2
Dec 13 '18 at 0:41
source share
 def factorial(n): result = 1 i = n * (n -1) while n >= 1: result = result * n n = n - 1 return result print (factorial(10)) #prints 3628800 
+1
May 14 '18 at 15:58
source share

I know that this question has been answered, but here is another method with understanding the reverse list of ranges, making the range easier to read and more compact:

  # 1. Ensure input number is an integer by attempting to cast value to int # 1a. To accomplish, we attempt to cast the input value to int() type and catch the TypeError/ValueError # if the conversion cannot happen because the value type is incorrect # 2. Create a list of all numbers from n to 1 to then be multiplied against each other # using list comprehension and range loop in reverse order from highest number to smallest. # 3. Use reduce to walk the list of integers and multiply each against the next. # 3a. Here, reduce will call the registered lambda function for each element in the list. # Reduce will execute lambda for the first 2 elements in the list, then the product is # multiplied by the next element in the list, and so-on, until the list ends. try : num = int( num ) return reduce( lambda x, y: x * y, [n for n in range(num, 0, -1)] ) except ( TypeError, ValueError ) : raise InvalidInputException ( "Input must be an integer, greater than 0!" ) 

You can see the full version of the code in this list: https://gist.github.com/sadmicrowave/d4fbefc124eb69027d7a3131526e8c06

+1
Nov 01 '18 at 20:40
source share

One line also works, fast and large numbers:

 #use python3.6.x for f-string fact = lambda x: globals()["x"] if exec(f'x=1\nfor i in range(1, {x+1}):\n\tx*=i', globals()) is None else None 
+1
Jan 22 '19 at 22:23
source share

Many of these methods are very good, but I would say that your best bet is to always use the built-in function. However, there are very easy to create if you want to see what happens. The quick one I came up with is almost the same as many of them here.

 def factorial(n): x = 1 li = list(range(1, n + 1)) for each in li: x = x * each print(x) 

This is pretty efficient code, the advantage is that the list is created if you are not manipulating some of the data from the list, although I'm not sure why you really do it.




Edit: just saw that I posted this on an old thing. Unfortunately.

0
Sep 15 '13 at 7:37
source share

Another way to do this is to use np.prod shown below:

 def factorial(n): if n == 0: return 1 else: return np.prod(np.arange(1,n+1)) 
0
Jun 29 '19 at 7:48
source share

The factorial of a positive integer n, denoted by n!, Is the product of all natural numbers less than or equal to n.

Formula: n! = n * (n-1) * (n-2) * (n-3) * (n-4) * ....... * 1 n! = n * (n-1) * (n-2) * (n-3) * (n-4) * ....... * 1

There are several ways to find factorial in python using the built-in function / library, etc. Here I created a custom function with a link to a basic factorial definition.

 def factorial(n): fact = 1 for i in range(1,n+1): fact = fact * i return(fact) print(factorial(4)) 

We can also implement the factorial function using the recursive technique, as shown below. But this method is only effective for small integer values. Because in recursion, the function is called repeatedly & memory space is required to support the stack, which is not an efficient or optimized approach for large integer values ​​to search for factorial.

 def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) print(factorial(4)) 
0
Aug 20 '19 at 9:48
source share
 def factorial(n): mul = 1 for i in range( 1, n + 1): mul *= i print(factorial(6)) 
0
Sep 08 '19 at 18:40
source share
 #use this code print("welcome to factoral program") factor = int(input("enter the number you want factors for")) factors = [] while factor > 0: factors.append(factor) factor -= 1 print(factors) 
-7
Dec 13 '13 at 9:35 on
source share



All Articles