+ 1
Why 120?
Hello everybody I run this could and I couldn't find any means why the result of this code is 120 until I come here. Can anybody explain why this code have such behaviour? def func (x) if x ==1: return 1 else: return x * func(x-1) print (func(5))
6 Answers
+ 6
This is the factorial function:
https://en.wikipedia.org/wiki/Factorial
Factorial for the integer 5 is noted as:
5 Ă 4 Ă 3 Ă 2 Ă 1
= 120
...hopefully you will get that resultđ
This approach is using a Recursive Function;
In our case the current result depends on the previous result, and the previous result depends on it's previous result, and so on... until we reach func(1) which is defined 1 by default.
func(n) = n * func(n-1)
func(5) = 5 * func(4)
func(4) = 4 * func(3)
...
func(1) = 1 (defined as default)
func(5) = 5*4*3*2*1 = 120
+ 5
It uses a principle known as recursion, setting up a base case and returning a function for other cases.
Here:
func(5)
Calls
5*func(4)
Calls
5*4*func(3)
Calls
5*4*3*func(2)
Calls
5*4*3*2*func(1)
(note 1 is our base case which returns 1)
Recursion terminates and
Expression evaluates to
5*4*3*2*1=120
+ 4
its recurring itself with number-1
and when it enters the base case it returns 1.
so 5*4*3*2*1= 120
+ 3
Watch this video:
https://www.youtube.com/watch?v=ozmE8G6YKww
A very simple explanation.
+ 3
its easy in each recursive calling save diferent value for n so when it arrive to base case then return back finishing operations
+ 1
it seems unanderstandable... can't understand that... theorically okay but in the code itself... the data... where is it stored in... don't understand that.... tried to compile... can't understand that... if you all can explain how code works I'm pleased