Lesson 7
Objects and Dictionaries
Chapter 6: Recursion
Hello again, Fibonacci!
Remember Fibonacci sequence from Lesson 6?
As a reminder, 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.
In Lesson 6, you have implemented an iterative version of the code. I’m sure you implemented it and did not skip it, did you? 🥺
Now, you will implement a recursive version of a Fibonacci number generator.
To simplify the problem a bit (so that you can concentrate on practising recursion), your function fibonacci()
should take a positive integer position
as input, and return an int
containing the Fibonacci number at the given position (starting from zero 0
).
For example:
- if the input is
0
, the function should return0
. - if the input is
1
, the function should return1
. - if the input is
2
, the function should return1
(0+1
). - if the input is
3
, the function should return2
(1+1
). - if the input is
4
, the function should return3
(1+2
). - if the input is
5
, the function should return5
(2+3
). - if the input is
6
, the function should return8
(3+5
). - etc.
Remember to test your program to make sure it works!
Again, think carefully about the problem on a piece of paper first before trying to implement anything! What is/are the base case(s)? What is/are the recursive case(s)?
Sample usage
>>> fibonacci(3)
2
>>> fibonacci(6)
8
>>> fibonacci(9)
34
>>> fibonacci(1)
1
>>> fibonacci(0)
0