rgb192
asked on
recursive calling function
def fib(x):
"""assumes x an int >= 0
Returns Fibonacci of x"""
assert type(x) == int and x >= 0,'wrong'
if x == 0 or x == 1:
return 1
else:
returnfib12=(fib(x-1) + fib(x-2))
return returnfib12
def testFib(n):
for i in range(n+1):
print ('fib of', i, '=', fib(i))
fib0=fib(0)
fib1=fib(1)
fib2=fib(2)
fib3=fib(3)
fib4=fib(4)
fib5=fib(5)
fib6=fib(6)
fib7=fib(7)
fib8=fib(8)
fib9=fib(9)
I modified code so I can see variables in debugger ide
returnfib12=(fib(x-1) + fib(x-2))
keeps on calling fib(x) function until finished
but there is no for or while loop
what is decrementing
returnfib12
*No Points*
To add to what aikimark says, you might see this termed and "exit condition". Without such a condition, your recursion will recur infinitely right up until the stack overflows. Any time you write a recursive function you have to make sure that an exit condition is present. The exit condition ensures that your recursion has a way to terminate.
Now, your exit condition is what aikimark referenced in his snippet. So how does it become true? Well, each time you call the recursive function, you are passing one less (and two less) than the current value. In other words, each time you call it (within itself), you are decrementing the value. At some point you will be passing in 1 as the value, at which point your exit condition will be met. At this point, each nested call returns to the outer call, all the way back up the call stack to the very first invocation of your function--i.e. the one that was called from outside this function.
To add to what aikimark says, you might see this termed and "exit condition". Without such a condition, your recursion will recur infinitely right up until the stack overflows. Any time you write a recursive function you have to make sure that an exit condition is present. The exit condition ensures that your recursion has a way to terminate.
Now, your exit condition is what aikimark referenced in his snippet. So how does it become true? Well, each time you call the recursive function, you are passing one less (and two less) than the current value. In other words, each time you call it (within itself), you are decrementing the value. At some point you will be passing in 1 as the value, at which point your exit condition will be met. At this point, each nested call returns to the outer call, all the way back up the call stack to the very first invocation of your function--i.e. the one that was called from outside this function.
To add what aikimark and kaufmed wrote, when constructing any recursive function, you should think the way that follows them mathematical definition. You may not be used to think that way when programming other things, because you usually think in terms of steps at the same level of nesting. However, when calling a function recursively, the inner local variable (here x) is different from the outer local variable. In mathematics, you would wrote x' = x - 1. Here is where the decrementing is done. The x - 1 is evaluated and the result is passed to the inner x.
You should really think in terms of the definition: "if x is 0 or 1, the result is 1. Otherwise the result is f(x-1) plus f(x-2)". It may be difficult to accept at first, but it is that way :)
A side note: Computing Fibonacci (or factorial or the like functions) recursively is extremely inefficient from computation point of view. Think only about fib(5) where the result is fib(4) + fib(3). Now fib(4) also calculates fib(3). And because one step calls the function twice (not considering the final steps), then the number of calculation is roughly like 2 ^ n where n is the argument of the most outer fib(). For fib(10), you can think about 1000 calculations. For fib(20), there is about 1 000 000 calculation.
Well, actually the number of steps may be very reduced by the final condition. Anyway, try the following modified example:
Recursive solutions may be very powerful when you have to tackle with problems formulated the way you think in mathematics/logic. But one have to be careful in cases like Fibonacci.
You should really think in terms of the definition: "if x is 0 or 1, the result is 1. Otherwise the result is f(x-1) plus f(x-2)". It may be difficult to accept at first, but it is that way :)
A side note: Computing Fibonacci (or factorial or the like functions) recursively is extremely inefficient from computation point of view. Think only about fib(5) where the result is fib(4) + fib(3). Now fib(4) also calculates fib(3). And because one step calls the function twice (not considering the final steps), then the number of calculation is roughly like 2 ^ n where n is the argument of the most outer fib(). For fib(10), you can think about 1000 calculations. For fib(20), there is about 1 000 000 calculation.
Well, actually the number of steps may be very reduced by the final condition. Anyway, try the following modified example:
#!python3
steps = 0
def fib(x):
global steps
steps += 1
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for n in range(31):
steps = 0 # must be set this way, because it is global for the fib()
print('fib({}) = {} ({} steps)'.format(n, fib(n), steps))
The global variable steps breaks the nesting rules -- it is not created as another local variable. This way, it can count the steps done on different levels of nesting. When runnig the code, you get the output:
fib(0) = 1 (1 steps)
fib(1) = 1 (1 steps)
fib(2) = 2 (3 steps)
fib(3) = 3 (5 steps)
fib(4) = 5 (9 steps)
fib(5) = 8 (15 steps)
fib(6) = 13 (25 steps)
fib(7) = 21 (41 steps)
fib(8) = 34 (67 steps)
fib(9) = 55 (109 steps)
fib(10) = 89 (177 steps)
fib(11) = 144 (287 steps)
fib(12) = 233 (465 steps)
fib(13) = 377 (753 steps)
fib(14) = 610 (1219 steps)
fib(15) = 987 (1973 steps)
fib(16) = 1597 (3193 steps)
fib(17) = 2584 (5167 steps)
fib(18) = 4181 (8361 steps)
fib(19) = 6765 (13529 steps)
fib(20) = 10946 (21891 steps)
fib(21) = 17711 (35421 steps)
fib(22) = 28657 (57313 steps)
fib(23) = 46368 (92735 steps)
fib(24) = 75025 (150049 steps)
fib(25) = 121393 (242785 steps)
fib(26) = 196418 (392835 steps)
fib(27) = 317811 (635621 steps)
fib(28) = 514229 (1028457 steps)
fib(29) = 832040 (1664079 steps)
fib(30) = 1346269 (2692537 steps)
That is almost 2 million calls for just 29, and about another one million of calculations for just one more. The recursive nesting also means eating the computer memory. And you will definitely observe it takes more and more time to compute. The alternative non-recursive solution (using a loop and more variables) needs about that many of loops how big is the argument -- very fast and no memory overhead when compared with the recursive solution.Recursive solutions may be very powerful when you have to tackle with problems formulated the way you think in mathematics/logic. But one have to be careful in cases like Fibonacci.
ASKER
so any
return a-1 is recurisive because of the minus -1
Does recursive happen in
fib
testfib
or both
return a-1 is recurisive because of the minus -1
Does recursive happen in
fib
testfib
or both
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
@kaufmed: Nice pictures. And the face :)
ASKER
in your first two cases (0 and 1), the function will return a 1 value because of this statement:
Try next case your self
Why is x incrementing?
http://filedb.experts-exchange.com/incoming/2014/08_w32/864334/Untitled.png
is this
fib3=fib(3)
Yes, that picture is fib(3). It was going to be a chore trying to lay that graphic out for anything greater than 3 = )
It isn't the case that x is incrementing. You are getting values returned from functions that are added to other function results, but the value of x should never increase once you make the call to the fib function.
When having difficulty to understand the recursion on the kaufmed pictures, just think as if the code in one rectangle was a code outside the fib definition. Just obscure the def fib(x): line. Think in terms that the code is outside of fib definition but accidentally it uses exactly the same statements and constructs. Let it have nothing common with the called fib(x-1) + fib(x-2). The result of the two fib() calls are summed. Suddenly, you may now remember that the result is returned as the result of the function call at the higher lever. It is actually not that important (for one step) if the above function has the same name. It is not visible from inside. However, it is important (that it has the same name) if you want to see a big picture.
As an experiment to understand recursion, try the following simpler recursive function:
This should help you to understand why a condition must be tested before the function is called recursively. Let's reformulate that example: "Printing n dots means... If there is anything to print (i.e. n >= 1) then print one dot and then print the tail of n-1 dots using the same rule."
As an experiment to understand recursion, try the following simpler recursive function:
#!python3
def fn():
print('.', end='', flush=True)
fn()
if __name__ == '__main__':
fn()
You have to be fast to see the beginning of the output:
c:\_Python\rgb192\Q_28489785>a.py
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
...................................Traceback (most recent call last):
File "C:\_Python\rgb192\Q_28489785\a.py", line 7, in <module>
fn()
File "C:\_Python\rgb192\Q_28489785\a.py", line 4, in fn
fn()
File "C:\_Python\rgb192\Q_28489785\a.py", line 4, in fn
fn()
[...snip...]
File "C:\_Python\rgb192\Q_28489785\a.py", line 4, in fn
fn()
File "C:\_Python\rgb192\Q_28489785\a.py", line 3, in fn
print('.', end='', flush=True)
RuntimeError: maximum recursion depth exceeded
The dotted lines is actually a single line wrapped in console. You are a kind of lucky, because Python allows only limited recursion depth (1000, could be set). Otherwise, the recursion would be infinite (actually until consuming all available memory). The extra arguments in the print cause printing the next dot just after the previous (no output of the end of the line), and to display the dot on the console as soon as possible (the flush=True, i.e. not waiting until the end of line).This should help you to understand why a condition must be tested before the function is called recursively. Let's reformulate that example: "Printing n dots means... If there is anything to print (i.e. n >= 1) then print one dot and then print the tail of n-1 dots using the same rule."
#!python3
def fn(n):
if n >= 1:
print('.', end='', flush=True)
fn(n-1)
if __name__ == '__main__':
fn(10)
Now, for your questions, the n is always decremented only. The dots are added one after another. The two phenomena are kind of unrelated.
ASKER
I errored in both python 2 and python 3
this error is in python 3
Message File Name Line Position
Traceback
<module> C:\Users\Acer\Documents\po rtable-pyt hon\myfile s\recur.py 7
fn C:\Users\Acer\Documents\po rtable-pyt hon\myfile s\recur.py 3
TypeError: 'flush' is an invalid keyword argument for this function
this error is in python 3
#!python3
def fn():
print('.', end='', flush=True)
fn()
if __name__ == '__main__':
fn()
Message File Name Line Position
Traceback
<module> C:\Users\Acer\Documents\po
fn C:\Users\Acer\Documents\po
TypeError: 'flush' is an invalid keyword argument for this function
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I liked Kaufmed pictures and the easy recursive simplified function the best to understand
thanks.
thanks.
and
fib(x-2)
============
in your first two cases (0 and 1), the function will return a 1 value because of this statement:
Open in new window
For your next case (2), the fib function will be invoked twice with a value of 1 and 0 (see above), which both return 1 values, which are added and the sum (2) is returned.
For your next case (3), the fib function is invoked twice with the value of 2 and 1. We see what happens when 2 is passed and when 1 is passed, so we add 2 and 1 and return 3.
try the next case (4) for yourself.