asked 63.4k views
4 votes
Write a function Fibonacci( N) to generate a list with a Fibonacci series of numbers, given the length of the series. The first two numbers in the series are 1 and 1 . Following these, each number of the series is calculated as the sum of the previous two numbers. The function should return the generated list

asked
User Dlwh
by
8.7k points

1 Answer

1 vote

Final answer:

The Fibonacci(N) function in Python generates a list containing a Fibonacci series of length N. It correctly handles cases where N is less than or equal to zero, or when N is 1, otherwise it appends the sum of the last two numbers in the current list until the desired length is reached.

Step-by-step explanation:

Write a Function to Generate Fibonacci SeriesTo write a function Fibonacci(N) that generates a list with a Fibonacci series of a given length N, you would start with the first two numbers in the series, which are 1 and 1. Every subsequent number in the series is the sum of the previous two numbers. Below is a sample code written in Python to accomplish this:

def Fibonacci(N):
if N <= 0:
return []
elif N == 1:
return [1]
fib_series = [1, 1]
while len(fib_series) < N:
next_value = fib_series[-1] + fib_series[-2]
fib_series.append(next_value)
return fib_series

This function first checks if N is less than or equal to zero, in which case it returns an empty list, as a series cannot have a negative or zero length. If N is 1, it returns a list containing only the first number of the Fibonacci series. Otherwise, the function initializes a list with the first two Fibonacci numbers and then enters a loop where it continues to append subsequent numbers by adding the last two numbers of the series until the list reaches the desired length N.

answered
User Rockbala
by
8.4k points

No related questions found