Question:
Fibonacci sequence is a sequence of numbers where the number at position i is the sum of the numbers at positions i-1 and i-2. Please implement a function to output a Fibonacci sequence, as a list of length n with n as the input of the function. Assume that the first two elements of the sequence are 0 and 1. If the input is 0 or less, please output an empty list.
Answer:
def fibonacci(n):
if n <= 0:
return []
# initial placeholder for the final result
res = [0,1]
# return the simple result if n is 1 or 2
if n == 1:
return res[0]
if n == 2:
return res
# loop for higher input
for i in range(2, n):
res.append(res[i-1] + res[i-2])
return res
# call the function
print(fibonacci(7))
👍 Have fun while coding with Python!
👌 Please subscribe to receive notifications on future challenges.
💬 If you have any questions simply write a comment down below.