0

Fibonacci

Hi everyone num = int(input()) def fibonacci(n): if n<= 1: return (n) else: return(fibonacci (n-1) + fibonacci (n-2) for i in range(5) print(i) #complete the recursive function fibonacci(num) Where is the mistake in my code for writing fibonacci ? Can u help me ?

8th Dec 2020, 1:01 PM
Qudrat Iskandarov
Qudrat Iskandarov - avatar
7 Antworten
+ 3
num = int(input()) def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) for i in range(num): print(fibonacci(i))
2nd Jan 2021, 11:15 PM
Jørgen Eliassen
Jørgen Eliassen - avatar
+ 2
Fibonacci has two initial conditions. When you use if n <= 1: return (n) You are returning a tuple with value of (1) when n is 1 and mistakenly returning a tuple (0) when n is 0. Fibonacci starts with two 1. So Your code should be if n <= 2: return 1
8th Dec 2020, 5:02 PM
Gordon
Gordon - avatar
+ 1
For reference here is the link to the code coach problem: https://www.sololearn.com/coach/574?ref=app Qudrat Iskandarov your fibonacci function would compute the sequence correctly. The challenge is how to make it print the numbers. The simplest way that I found was to think of this fibonacci() function as only a printing function. It is a simple loop. In that loop it calls a subfunction, defined inside fibonacci(), that does the recursive calculation.
8th Dec 2020, 2:09 PM
Brian
Brian - avatar
0
Need extra ) at the return statement in else. Also, if you need only fibonacci of num. The entire for loop is redundant.
8th Dec 2020, 1:52 PM
你知道規則,我也是
你知道規則,我也是 - avatar
0
The result should be like that 0 1 1 2 3
8th Dec 2020, 5:10 PM
Qudrat Iskandarov
Qudrat Iskandarov - avatar
0
i would love to figure this out as well, i have the code correct but it never accounts for 0. i tried to force print 0 in the beginning but it isn’t recognizing it as valid
30th Dec 2020, 4:09 PM
CmplXty
0
here is what i put which works however it wont finish the challenge x, y = 1, 0 # Assigns starting numbers print(y) print(x) for i in range(100): # Generates 100 numbers print(x + y) # Number in sequence = previous 2 added together x, y = x + y, x
30th Dec 2020, 4:10 PM
CmplXty