+ 1
How does this recursive program works??
if x == 0 or x == 1: return 1 else: a = fib(x-1) + fib(x-2) print(fib(x-1),"+",fib(x-2)) return a print(fib(4)) Does fib(x-1) + fib(x-2) recursive at same time??
4 Answers
+ 1
@Harm: You're right. I've updated my answer. I didn't think OP meant it literally.
0
No, first the first one then the second, but it happens very quickly so you won't notice,, especialy when running over one thread
0
Yes. It calls fib() inside fib().
[Edit: I mean "yes" as in it runs all recursive calls on the same stack. Sorry if I've misunderstood the question. I thought it was about understanding recursive functions, not their execution. FYI: Many interpreters read ahead and resolve recursive calls to prevent overflows, AFAIK]
Here's a *simple* example:
def func(a):
if (a < 5):
print(a)
a += 1
func(a)
else:
print(str(a) + " done here")
return a
func(2)
The above prints 2, then 3, then 4, and stops at 5
It's like a loop almost. This paradigm is more expressive and for coding scientific things. You may briefly stumble across recursive functions in lower-level graphical programming too. Basically, I wouldn't worry too much about understanding it deeply. So long as you could pass a basic test on it.
0
nothing runs AT the same time of you aren't threading or something.. it happens in order