How to realize factorial in Python
This article mainly introduces how to achieve factorial in Python, which is very detailed and has certain reference value. Friends who are interested must finish it!
I believe everyone is no stranger to factorials. If you don't know the factorial, you can see here:
The factorial of a number:
For example, the factorial of 5
Recursive functions are generally recommended for most tutorials in python:
#! / usr/bin/python3 "" Python2,3 can both "def factorial (n): # body function if n = = 1: return 1 return n * factorial (NMub 1) res = input (" Please enter n: ") print (factorial (res))
But this is not only inconvenient to read, but also may cause stack overflow when n is very large.
Factorial (1000) Traceback (most recent call last): File "", line 1, in File "", line 4, in factorial [Previous line repeated 995 more times] File ", line 2, in factorialRecursionError: maximum recursion depth exceeded in comparison
So I prefer this:
#! / usr/bin/pythonli = [] def factorial (n): global li result = 1 for i in range (n): li.append (iTun1) for j in li: result = result * j return resultprint (factorial (int ("Please enter n:"))
By storing a single list, memory usage can be effectively reduced, and this call takes up only a few stacks and does not cause an overflow.
Or there are functions in the math module that can be used:
Import matha = input ("N:") fac = math.factorial (a) print (fac)
Or very simple for:
# Chinese variable name is legal! # Chinese variable name is legal! Number = input ("number:") a = 1for i in range (1, number + 1): a = a * iprint (a) above is all the content of this article "how to achieve factorial in Python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!