How does this recursive program works?? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 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??

27th Jun 2017, 10:01 AM
S.Naveen Kumar
S.Naveen Kumar - avatar
4 Réponses
+ 1
@Harm: You're right. I've updated my answer. I didn't think OP meant it literally.
27th Jun 2017, 12:49 PM
Jamie
Jamie - avatar
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
27th Jun 2017, 10:55 AM
Harm Zeinstra
Harm Zeinstra - avatar
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.
27th Jun 2017, 11:10 AM
Jamie
Jamie - avatar
0
nothing runs AT the same time of you aren't threading or something.. it happens in order
27th Jun 2017, 12:02 PM
Harm Zeinstra
Harm Zeinstra - avatar