python - Understanding factorial recursion -
i'm looking on factorial example of recursion , make sure i'm understanding correctly!
def factorial(n): if(n == 0): return 1 else: return n * factorial(n-1)
would right in saying:
factorial(4) = factorial(4-1) * 4 = factorial(3-1) *3 *4 = factorial(2-1) *2 *3 *4 = factorial(1-1) *1 *2 *3 *4 = 24
because factorial(1-1) = factorial(0) base case shows = 1 , multiply 2, 3 4.
is correct way of looking @ it?
thanks in advance!
yes is. since it's recursion, works opposite way. once had interviewer explain me :
say, fact(5) :
- fact(5) = 5 * fact(4) - fact(4) = 4 * fact(3) - fact(3) = 3 * fact(2) - fact(2) = 2 * fact(1) - fact(1) = 1 * fact(0) - fact(0) = 1 // condition returns 1.
now, imagine -
sign above stands return. return whatever after -
sign. lowest line, 1 returned. then, have 1 returned in fact(1) i.e. 1 * 1. happens in reverse cascade :
= 120 - fact(5) = 5 * 24 - fact(4) = 4 * 6 = 24 - fact(3) = 3 * 2 = 6 - fact(2) = 2 * 1 = 2 - fact(1) = 1 * 1 = 1 - fact(0) = 1
remember whenever work on recursion, works in reverse. should breaking recursion problem down.
this why tail recursion , related optimization important. in memory, each of calls delayed , can't return until calls above (below in diagram) finish , return. deep recursive call can cause stack overflow unless compiler/interpreter optimize turning version in op, such partial results evaluated , not delayed. python not perform optimization , must careful recursive calls.
Comments
Post a Comment