- 3 способа вычислить факториал в Python
- Введение
- Вычисление факториала циклом while
- Цикл while
- Цикл for
- Вычисление факториала Рекурсией
- Вычисление факториала методом factorial()
- Заключение
- Python Factorial Examples
- The Python Factorial function
- Using math.factorial()
- Using an Iterative Procedure
- Using a Recursive Procedure
- Tail Recursive Calls
- Conclusion
- References
- Python Factorial Function: Find Factorials in Python
- What are Factorials and Why Do They Matter?
- How to Calculate Factorials with Python’s Math Module
- How To Create a Function To Calculate Factorials with Recursion
- Using a For Loop to Calculate Factorials in Python
- Conclusion
- Additional Resources
3 способа вычислить факториал в Python
Статьи
Введение
В ходе статьи рассмотрим 3 способа вычислить факториал в Python.
Вычисление факториала циклом while
Цикл while
Для начала дадим пользователю возможность ввода числа и создадим переменную factorial равную единице:
number = int(input('Введите число: ')) factorial = 1
Как мы знаем, факториал – это произведение натуральных чисел от единицы до числа n. Следовательно создадим цикл, который не закончится, пока введённое пользователем число больше единицы. Внутри цикла увеличиваем значение в переменной factorial умножая его на переменную number, после чего уменьшаем значение в number на единицу:
number = int(input('Введите число: ')) factorial = 1 while number > 1: factorial = factorial * number number = number - 1 print(factorial) # Введите число: 10 # 3628800
Цикл for
Обычно способ нахождения факториала при помощи цикла for не рассматривается, но почему бы и нет. Принцип не сильно отличается от цикла while, просто приравниваем значение введённое пользователем к переменной factorial, а в цикле указываем количество итреаций начиная с единицы, и заканчивая введённым числом:
number = int(input('Введите число: ')) factorial = number for i in range(1, number): factorial = factorial * i print(factorial) # Введите число: 5 # 120
Вычисление факториала Рекурсией
Для вычисления факториала про помощи рекурсии, создадим функцию factorial(), и в качестве аргумента передадим number:
Внутри функции добавим условие, что если переданное число в аргумент number равняется единице, то возвращаем его. Если же условие не сработало, то вернётся аргумент number умноженный на вызов функции factorial() с передачей аргумента number – 1:
def factorial(number): if number == 1: return number else: return number * factorial(number - 1)
Дадим пользователю возможность ввода, вызовем функцию и выведем результат в консоль:
def factorial(number): if number == 1: return number else: return number * factorial(number - 1) print(factorial(int(input('Введите число: ')))) # Введите число: 7 # 5040
Вычисление факториала методом factorial()
В стандартном модуле math есть специальный метод для вычисления факториала под названием factorial(). Используем его для нахождения факториала:
from math import factorial number = int(input('Введите число: ')) print(factorial(number)) # Введите число: 4 # 24
Заключение
В ходе статьи мы с Вами рассмотрели целых 3 способа вычислить факториал в Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂
Python Factorial Examples
In this article, we’ll look at how we can calculate the Python factorial using different approaches.
The Python Factorial function
The Python factorial function factorial(n) is defined for a whole number n . This computes the product of all terms from n to 1 . factorial(0) is taken to be 1 .
factorial(n) = n * (n-1) * (n-2) * . * 1, n >= 1 factorial(n) = 1, n = 0
Therefore, factorial(4) = 4 * 3 * 2 * 1 = 24.
Let’s analyze how we can write this mathematical function in Python.
Using math.factorial()
We can directly use the math module’s factorial function to do the work for using:
import math def factorial(x): return math.factorial(x) print(factorial(5))
We’ll also look at finding this function using other methods: let’s use an iterative procedure now.
Using an Iterative Procedure
We can directly loop over all the numbers for 1 to n and directly multiply the product.
def factorial(n): if n == 0: return 1 prod = 1 for i in range(1, n+1): prod = prod * i return prod if __name__ == '__main__': print(factorial(4)) print(factorial(7))
Let’s now look at using a recursive method for the Python factorial function.
Using a Recursive Procedure
We can utilize recursion, to compute this function. Basically, we reduce this function into a smaller sub-problem. After we compute the sub-problems, we can combine the results to give the final answer.
Since the problem structure is a decreasing product, we can model the recursion in the following manner:
factorial(n) = n * factorial(n-1), n >= 1 factorial(0) = 1, n = 0
The last line is the base case. This is the point where the recursion stops, and we can get the final product, when the recursion unwinds.
We’ll write the corresponding Python function for this:
def factorial(n): if n == 0: # Base case n = 0 return 1 else: # Use the definition of factorial function return n * factorial(n-1) if __name__ == '__main__': print(factorial(4)) print(factorial(7))
That seems to be correct. Let’s analyze what actually happens in the recursion calls.
Whenever recursion calls are used, there is a call stack, which continuously stores the state of the program, until the base case is reached. The stack elements are finally popped out one by one after a value is returned by the corresponding block, when the recursion unwinds from n = 0 .
The whole process is explained in the below figure, for finding fact(3) . The first part of the entire process is the build-up of the stack where each of those recursive calls is stacked on top of each other until the function returns 1.
Once the function can no longer recursively call, it starts calculating the factorial as demonstrated below.
When the functions return, the stack elements get popped out one by one, from the top. When it finally reaches the main() stack, the function is finally complete, and we have our value, which comes out to be 6 .
Tail Recursive Calls
While our program works fine, the problem with our recursive function is that the stack size grows as much as the input size.
So if n is a very large number, our recursion stack may be very large, that that may cause the stack to overflow! To avoid this, we’ll use another approach to coding a recursive function, called a tail-recursive procedure.
The tail procedure call aims to perform the recursion call after computing the intermediate result. So, instead of increasing the stack size, the program can use the same stack for the whole process! It only needs to be updated.
This means that our recursive call must always be at the end. This is why it is a “tail call”.
def fact_helper(accum, n): if n == 0: return accum return fact_helper(accum*n, n-1) def factorial(n): return fact_helper(1, n) if __name__ == '__main__': print(factorial(4)) print(factorial(7))
Since we cannot directly make the recursive call at the end, we do it with another helper function, that does that actual computation for us. This helper function stores an accumulator , which stores the current value of the function.
The trick is to pass the accumulator as a parameter to the recursive function, and update it, using accum*n . This way, we will store the intermediate state in one variable, and hence, only in one stack frame!
You get the same output as before! Now, you’ve also ensured that the program uses only one stack frame, so it is essentially equivalent to the iterative procedure! Isn’t that nice?
Conclusion
In this article, we learned about how we can implement the factorial function in different ways, using the math module, as well as through both iteration and recursion.
References
Python Factorial Function: Find Factorials in Python
In this tutorial, you’ll learn how to calculate factorials in Python. Factorials can be incredibly helpful when determining combinations of values. In this tutorial, you’ll learn three different ways to calculate factorials in Python. We’ll start off with using the math library, build a function using recursion to calculate factorials, then use a for loop.
By the end of this tutorial, you’ll have learned:
- What factorials are and why they’re important
- How to use for loops to calculate factorials
- How to build a recursive function to calculate factorials
What are Factorials and Why Do They Matter?
The factorial of a number is calculated as the product of all the integers from 1 to that number. Factorials are displayed as the number followed by an exclamation mark. For example, the factorial for the number 7 is 7! .
Let’s see what this means and how we can calculate the factorial for 7! :
7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040
There are some important things to note about factorials:
At this point, you may be wondering what the point of factorials is. Factorials allow us to calculate how many combinations or orderings of different items are. Given a list of, say, three items such as [1,2,3] , there are 3! different combinations of the data.
Similarly, factorials allow us to find permutations of subsets. Say we wanted to find the number of combinations that a group of 10 people could come into first, second, and third place. With this, we could use the formula 10! / (10-3)! , which reduces down to 10! / 7! , which further reduces to 10 * 9 * 8 = 720 combinations.
How to Calculate Factorials with Python’s Math Module
One of the simplest ways to calculate factorials in Python is to use the math library, which comes with a function called factorial() . The function returns a single integer and handles the special case of 0! . Similarly, the function error handles when attempting to find the factorial of a negative number.
Let’s try finding the factorial of 7 using the math library:
# Finding Factorials with math.factorial() import math print(math.factorial(7)) # Returns: 5040
Similarly, let’s try getting the factorial of a negative number:
# Finding the factorial of a negative number import math print(math.factorial(-7)) # Raises: ValueError: factorial() not defined for negative values
In the next section, you’ll learn how to create a function to calculate factorials in Python.
How To Create a Function To Calculate Factorials with Recursion
In this section, you’ll learn how to create a function that calculates factorials with recursion. Building this function recursively allows you to define a function that is simple and elegant. Let’s see how this function looks and then explore how it works:
# Building a recursive function to calculate factorials def factorial(number): if number < 2: return 1 else: return number * factorial(number - 1) print(factorial(7)) # Returns: 5040
If you’re not familiar with recursion (or just want a refresher on how it works), let’s break down the steps that the function takes:
- The function takes a single argument, number
- If the number is less than 2 (meaning: 1), it returns 1. This is the closing case which doesn’t call itself.
- If the number is 2 or higher, then the function returns that number multiplied by the value returned when the function is called again for that number minus 1.
If this is a bit mind-bending, don’t worry – you’re not alone! Let’s break this down a little further. Let’s imagine we call the function with the number of 3:
- The function returns 3 * factorial(2)
- This, in turn, returns 2 * factorial(1)
- This, then returns 1
We can then move back up our chain where we now get: 1 * 2 * 3 , which equals 6! In the next section, you’ll learn how to use a for loop to calculate factorials in Python.
Using a For Loop to Calculate Factorials in Python
In this final section, we’ll use a for loop to calculate a factorial of a number in Python. This can be a more readable and approachable approach to calculating factorials than recursion. It also doesn’t require any additional libraries, which can be helpful in programming interviews!
We’ll use the augmented assignment operator to make our code a little slimmer. Let’s see what this looks like:
# Using For Loops to Calculate Factorials def factorial(number): num = 1 for i in range(1, number+1): num *= i return num print(factorial(7)) # Returns: 5040
In this section, you learned how to use for loops to calculate factorials in Python.
Conclusion
In this tutorial, you learned about factorials in Python. You learned what factorials are and why they’re important. You then learned three different ways of calculating factorials. First, you learned how to calculate factorials with the Python math library. Then, you learned how to calculate factorials using a recursive function. Finally, you learned how to use for loops to calculate factorials.
Additional Resources
To learn more about related topics, check out the tutorials below: