0

Write a fibonacci function that takes a number n (serial number) and returns a number from a list of Fibonacci numbers. Solve the problem with recursion. Hint: Fibonacci numbers are a sequence of numbers where each element is calculated as the sum of the previous two. The sequence itself starts like this: 0, 1, 1, 2, 3, 5, 8, 13, ...

Example: answer = fibonacci(5) print(answer) # 3

answer = fibonacci(6) print(answer) #5

I did it, but I don't know how to make a list start with zero Can you help me?

def fibonacci(n):
    if n in (1, 2):
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)

n = int(input("n = "))
print(fibonacci(n))
1
  • 2
    If n is 1 you should return 0, if n is 2 you should return 1. Commented Jul 25, 2022 at 19:44

1 Answer 1

1

Change your base condition to

if n in (1, 2):
   return n-1

to make sure you are counting 0 as well (as stated in the comment)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.