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 ?
7 odpowiedzi
+ 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))
+ 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
+ 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.
0
Need extra ) at the return statement in else.
Also, if you need only fibonacci of num. The entire for loop is redundant.
0
The result should be like that
0
1
1
2
3
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
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