+ 1
how this code function?
guys im doing the python course and i am at recursion. this code is a code of a exercise and the result is 5 but i don't know how this code function. can anyone say me how it works? thanks 0 Pl def fib(x) : if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2)
3 ответов
+ 2
Simone
def fib(x) :
if x == 0 or x == 1:
return 1
else:
return fib(x - 1) + fib(x - 2)
print (fib(4))
#fib(3) + fib(2)
#fib(2) + fib(1) + fib(1) + fib(0)
#fib(1) + fib(0) + fib(1) + fib(1) + fib(0)
#1 + 1 + 1 + 1 + 1
#5
+ 2
This is an example of recursive function. A recursive function is a function which calls itself repeatedly until a termination condition is met, after when it returns a value. Here your function works as below for the call fib(4):
fib(4)
fib(3) + fib(2)
fib(2)+fib(1) + fib(1)+fib(0)
fib(2)+ 1 + 1 + 1
fib(1)+fib(0) + 3
1 + 1 + 3
5
And finally return the value 5. Hope you understood =)
0
ok thank very much, now i understand