Lesson 6
Dealing with Sequences of Objects
Chapter 5: Applied problem solving
Fibonacci sequence
Building on from the previous challenge, you will now write a function to generate a Fibonacci sequence.
The Fibonacci sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … The first numbers are 0 and 1, and then each subsequent number is the sum of the two preceding numbers.
Now, write a function generate_fibonacci()
that takes an integer length
as input, and returns a list containing the Fibonacci sequence up until the given length
.
For example, if the input is 6
, the function should return [0, 1, 1, 2, 3, 5]
.
You can use while
or for
loops to solve this challenge.
As usual, remember to test your program!
Sample usage
>>> generate_fibonacci(4)
[0, 1, 1, 2]
>>> generate_fibonacci(7)
[0, 1, 1, 2, 3, 5, 8]
>>> generate_fibonacci(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> generate_fibonacci(1)
[0]
>>> generate_fibonacci(0)
[]