Thursday, August 18, 2022

[FIXED] Where is the mistake in my code ( Fibonacci)?

Issue

that is the code (I use python 3):

def fibonacci(x):
  if x == 1 or 2:
    return 1
  f = fibonaci(x-1) + fibonaci(x-2) 
  return f

print(fibonacci(4))

What I would like to get as an output is 3, which is the fourth Fibonacci number. However I get 1 as an output.

f = fibonaci(x-1) + fibonaci(x-2)

I think that code does not do what I want it to do. Lets say I would take fibonacci(3) as my input.

What I think should happen:

f = fibonacci(3-1) + fibonacci(3-2)

fibonacci(3-1) and fibonacci(3-2) should both return 1 right? so f should be = 2 and fibonacci(3) should give me 2 as an output. But what I get as an output is still 1. Where is the mistake?


Solution

The mistake is in your if clause. What you meant was probably this:

if x == 1 or x == 2:

as if 2 is always "true", so for any x you will be getting 1.

However, this will still be wrong, as in Fibonacci sequence the first two numbers are 0 and 1, so:

if x <= 1:
    return x


Answered By - VisioN
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.