Question: I am struggling to write a python code for this: The Fibonacci sequence begins with 0 and then 1 follows. All subsequent values are the
I am struggling to write a python code for this:
The Fibonacci sequence begins with 0 and then 1 follows. All subsequent values are the sum of the previous two, ex: 0, 1, 1, 2, 3, 5, 8, 13. Complete the fibonacci() function, which has an index n as parameter and returns the nth value in the sequence. Any negative index values should return -1.
Ex: If the input is:
7 the output is:
fibonacci(7) is 13 Note: Use a for loop and DO NOT use recursion.
This is what i have so far:
def fibonacci(n): if n < 0: return -1
# Initialize the first two values in the sequence fib_sequence = [0, 1]
# Generate the Fibonacci sequence up to the nth index for i in range(2, n + 1): next_value = fib_sequence[i - 1] + fib_sequence[i - 2] fib_sequence.append(next_value)
return fib_sequence[n]
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
