0

Почему код не работает? Решено. Solved.

Почему данный код не работает? Хотел вычислить последовательность фибоначчи рекурсивно, но код не работает должным образом. https://code.sololearn.com/c2KX0b7oKRMx/?ref=app

18th Dec 2020, 1:55 PM
😎_M_😎
😎_M_😎 - avatar
5 Answers
+ 2
n1 = 0 n2 = 1 sum = 0 def fibonacci(x): global n1,n2,sum #using global values if x == 10: return x else: print(sum) sum = n1 + n2 n1 = sum n2 = n1 - n2 return fibonacci(x+1) print(fibonacci(0)) Edit : #😎_M_😎 #В вызове функции каждый раз, когда ваши значения n1, n2 начинаются с 0,1 в каждом рекурсивном вызове .. Поэтому объявляйте их глобально или передавайте обновленные значения в рекурсивных вызовах .. (translated this) In function call every time your n1, n2 values are starting from 0,1 in each recursive callings.. So declare those globally or pass updated values in recursive callings.. In passing way do like : def fibonacci(n1, n2, x) :
18th Dec 2020, 2:04 PM
Jayakrishna 🇮🇳
+ 1
I updated with explanations, hope you understand it.. 😎_M_😎 you're welcome..
18th Dec 2020, 2:14 PM
Jayakrishna 🇮🇳
+ 1
In your function defination, functions get executed from start line line: def fibonacci(x) : to end line sequentially, and your 1st 3lines n1=0,n2=1,sum=0 will be executed every time you call it first. Even in recursive calls also these will be execution first so n1, n2,sum updated values gets resetted. So you shloud pass updated values like you passing x value (updated x as x+1).. Or use global values... hope it clears..
18th Dec 2020, 9:17 PM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳, Thank you very much!
18th Dec 2020, 2:12 PM
😎_M_😎
😎_M_😎 - avatar
0
Jayakrishna🇮🇳, I have one question. Why are the values not updated in recursive calls? They should be updated, it is logical.
18th Dec 2020, 2:18 PM
😎_M_😎
😎_M_😎 - avatar