Structures de données et algorithmes en Python
Miriam Antona
Software engineer
$n!$
$n!=n$ · $(n-1)$ · $(n-2)$ · $...$ · $1$
$5!=$ $5$ · $4$ · $3$ · $2$ · $1=120$
def factorial(n):
result = 1
while n > 1:
result = n * result
n -= 1
return result
factorial(5)
120
$n!= n$ · $(n-1)!$
def factorial_recursion(n):
return n * factorial_recursion(n-1)
def factorial_recursion(n): if n == 1:return 1else:return n * factorial_recursion(n-1)
print(factorial_recursion(5))
120
factorial(5) démarrefactorial(5) -> factorial(4) démarrefactorial(4) -> factorial(3) démarre
factorial(5) démarrefactorial(5) -> factorial(4) démarrefactorial(4) -> factorial(3) démarrefactorial(3) -> factorial(2) démarre
factorial(5) démarrefactorial(5) -> factorial(4) démarrefactorial(4) -> factorial(3) démarrefactorial(3) -> factorial(2) démarrefactorial(2) -> factorial(1) démarre
factorial(5) démarrefactorial(5) -> factorial(4) démarrefactorial(4) -> factorial(3) démarrefactorial(3) -> factorial(2) démarrefactorial(2) -> factorial(1) démarre
factorial(1) se terminefactorial(2) se termine
factorial(1) se terminefactorial(2) se termine
factorial(1) se terminefactorial(2) se terminefactorial(3) se termine
factorial(1) se terminefactorial(2) se terminefactorial(3) se terminefactorial(4) se termine
factorial(1) se terminefactorial(2) se terminefactorial(3) se terminefactorial(4) se terminefactorial(5) se termine
factorial(1) se terminefactorial(2) se terminefactorial(3) se terminefactorial(4) se terminefactorial(5) se termine
Structures de données et algorithmes en Python