Structuri de date și algoritmi în 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) porneștefactorial(5) să termine -> factorial(4) porneștefactorial(4) să termine -> factorial(3) pornește
factorial(5) porneștefactorial(5) să termine -> factorial(4) porneștefactorial(4) să termine -> factorial(3) porneștefactorial(3) să termine -> factorial(2) pornește
factorial(5) porneștefactorial(5) să termine -> factorial(4) porneștefactorial(4) să termine -> factorial(3) porneștefactorial(3) să termine -> factorial(2) porneștefactorial(2) să termine -> factorial(1) pornește
factorial(5) porneștefactorial(5) să termine -> factorial(4) porneștefactorial(4) să termine -> factorial(3) porneștefactorial(3) să termine -> factorial(2) porneștefactorial(2) să termine -> factorial(1) pornește
factorial(1) se terminăfactorial(2) se termină
factorial(1) se terminăfactorial(2) se termină
factorial(1) se terminăfactorial(2) se terminăfactorial(3) se termină
factorial(1) se terminăfactorial(2) se terminăfactorial(3) se terminăfactorial(4) se termină
factorial(1) se terminăfactorial(2) se terminăfactorial(3) se terminăfactorial(4) se terminăfactorial(5) se termină
factorial(1) se terminăfactorial(2) se terminăfactorial(3) se terminăfactorial(4) se terminăfactorial(5) se termină
Structuri de date și algoritmi în Python