Omnimaga
General Discussion => Technology and Development => Computer Programming => Topic started by: runeazn on January 27, 2012, 03:53:18 pm
-
So im followign a guide but i dont get it D:
let say we have
def factorial(number):
if number <=1 #base case
return=1
else:
return number*factorial(number-1)
the return 1 part wont it keep continue repeating the process of putting 1 in the factorial to infinty?
or am i reading it wrong?
or if it returns 1 then that means no matter what factorial(x)= 1
??
-
"return=1" exits out of the function and displays the number 1 IIRC
and the other return:
return number*factorial(number-1)
using an example of number=two:
if number <=1 #base case //2>1, therefore it ignores this statement
return=1
else: //else...
return number*factorial(number-1) // it returns 2*factorial(number-1) //2*1
-
Lets break it down, lets see what happens when we try factorial(3).
We call factorial(3), and since 3 is larger than 1, it returns 3*factorial(3-1).
but before we get an answer we need to calculate the factorial of 3-1 (2). Lets do that.
we call factorial(2), and since 2 is larger than 1, it returns 2*factorial(2-1).
So now we need to calculate the factorial of 2-1 (1). This would be
We call factorial(1), and since 1 is equal to 1, it returns 1.
So moving backwards, we have:
factorial(1) = 1;
factorial(2) = 2*factorial(1) = 2*1;
factorial(3) = 3*factorial(2) = 3*2*factorial(1) = 3*2*1;
Make a bit more sense? This is the way recursive functions work, they call themselves multiple times with different numbers to get a final answer.
-
i dont see anywhere it will fill in the 1?
or will it automatically do when returning the 1 ,
number =1?
-
I'm not quite sure I understand your question? When number is 1, the If statement is true and therefore the method simply returns 1. When the number is not 1, it returns the current number multiplied by the factorial of the next lowest number.
-
it returns 1 but where does it return the 1 to?
to the number so it can go into the factorial or does it return 1 to i dunno?
-
It returns the 1 to wherever called it. That location could either be inside the function itself, or somewhere else. If I call factorial(1), it returns the 1 to me, but if I call factorial(2) it returns the 1 to the first factorial() method.