+ 3

Pls help me in solving Fibonacci in python. Its literally hard. My output is not matching the test cases.

num = int(input()) def fibonacci(n): if n <= 1: return 1 else : return n + fibonacci(n - 1) print(fibonacci(num))

22nd May 2021, 11:32 AM
Ritesh Behera
Ritesh Behera - avatar
16 Réponses
+ 3
num = int(input()) def fib(n): if n <= 2: return 1 else: return fib(n-1) + fib(n-2) print(fib(num)) visph
22nd May 2021, 9:50 PM
6hpxq9
6hpxq9 - avatar
+ 2
Fibonacci series have 2 initial numbers,and next number is sum of previous 2 numbers.. 0,1, 0+1=1, 1+1=2, 2+1=3,... edit: your code working for sum of N numbers.. edit: Ritesh Behera You have to try it.. you already have an example code in above post. Take 3 variables n1,n2,n3. 2 have initial values and n3=n1+n2; change values of n1 to n2, n2 to n3 .. repeat this till input number.
22nd May 2021, 11:41 AM
Jayakrishna 🇮🇳
+ 2
recursive but inefficient solution with only one argument: def fib(n): if n<2: return 1 return fib(n-1)+fib(n-2)
22nd May 2021, 4:39 PM
visph
visph - avatar
+ 2
num = int(input()) firstN = 0 secondN = 1 thirdN = 0 for i in range(num): thirdN = firstN + secondN print(f"{thirdN}") firstN = secondN secondN = thirdN I Made this and hope u enjoy it ;)
22nd May 2021, 9:29 PM
6hpxq9
6hpxq9 - avatar
+ 2
6hpxq9 OP said "But we have to do it recursively" ^^
22nd May 2021, 9:39 PM
visph
visph - avatar
+ 2
6hpxq9 I didn't say you've copied it, I just mean that it's unuseful ^^
22nd May 2021, 10:04 PM
visph
visph - avatar
22nd May 2021, 11:34 AM
Sâñtôsh
Sâñtôsh - avatar
+ 1
I know that but how to output the same
22nd May 2021, 11:44 AM
Ritesh Behera
Ritesh Behera - avatar
+ 1
But we have to do it recursively
22nd May 2021, 12:43 PM
Ritesh Behera
Ritesh Behera - avatar
+ 1
Can you add full question as it is..? Recursively you can do it like pass 2 values find next and return 3rd value for nth time otherwise recall with new values ... Or Do find next value until calling function n times recursively... Like if(n<=0) return n3 Else n2,n1=n3,n2 n-=1 Fibonacci(n1,n2)
22nd May 2021, 12:54 PM
Jayakrishna 🇮🇳
+ 1
6hpxq9 less consisely, that's the exact code I posted sooner, adding a fault by checking for n<=2 instead of n<2 (related to OP code in description) ;P
22nd May 2021, 9:54 PM
visph
visph - avatar
0
visph I just made it like 1 year ago, get calm, bro ._.
22nd May 2021, 10:02 PM
6hpxq9
6hpxq9 - avatar
- 1
Koi easy wala hai to batana
22nd May 2021, 11:40 AM
Ritesh Behera
Ritesh Behera - avatar
- 1
Ritesh Behera your recursion is incorrect, is fibonacci (n-1) + (n-2)
24th May 2021, 10:51 AM
karimireza77
karimireza77 - avatar
- 2
Santos ye mere test case se match nhi hoga
22nd May 2021, 11:40 AM
Ritesh Behera
Ritesh Behera - avatar
24th May 2021, 9:26 AM
Cyberoam Fire Gaming
Cyberoam Fire Gaming - avatar