+ 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))
16 Respuestas
+ 3
num = int(input())
def fib(n):
if n <= 2:
return 1
else:
return fib(n-1) + fib(n-2)
print(fib(num))
visph
+ 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.
+ 2
recursive but inefficient solution with only one argument:
def fib(n):
if n<2: return 1
return fib(n-1)+fib(n-2)
+ 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 ;)
+ 2
6hpxq9 OP said "But we have to do it recursively" ^^
+ 2
6hpxq9 I didn't say you've copied it, I just mean that it's unuseful ^^
+ 1
I know that but how to output the same
+ 1
But we have to do it recursively
+ 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)
+ 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
0
visph I just made it like 1 year ago, get calm, bro ._.
- 1
Koi easy wala hai to batana
- 1
Ritesh Behera your recursion is incorrect, is fibonacci (n-1) + (n-2)
- 2
Santos ye mere test case se match nhi hoga