1.)
consider the function
Code:
def infinite_recursion():
return infinite_recursion()
if we write this infinite recursive function then it gives the error:
Code:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in infinite_recursion
...
with the final line repeating over and over.
if we just have an infinitely repeating loop. ie:
we never get an error, and it just keeps repeating the loop, doing as its told.
2.)
recursive function to generate $\displaystyle \sum_{i=1}^n i$
Code:
def n_sum(n):
if n <= 1: return 1 #base case
return n+n_sum(n-1) #inductive step
for fibonacci sequence: Code:
def nth_fib(n):
if n <= 1: return 1 #covers our base cases
return nth_fib(n-1) + nth_fib(n-2) #inductive step
for fib(0) and fib(1) we call our function once only (as it is covered in the base case)
for fib(n) we call our function how many times it calls for both $\displaystyle n$ and $\displaystyle n-1$
so $\displaystyle calls(n) = calls(n-1) + calls(n-2)$
this is the
fibonacci relation, and we have the same initial cases:
$\displaystyle calls(0) = calls(1) = 1$
so $\displaystyle calls(n) = fib(n)$
ie the function is called 8 times with fib(5).