27. The nth Fibonacci number
The Fibonacci numbers are a sequence that starts with 0 and 1. Each number after that is the sum of the two before it:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
Write a function fib(n) that takes a whole number n and returns the Fibonacci number at position n, counting
from 0: fib(0) is 0, fib(1) is 1 and fib(2) is 1.
It must be fast. n goes up to 90, and the plain recursive version, fib(n - 1) + fib(n - 2), would take years to
get there: it works out the same numbers again and again. Your code has to answer fib(90) in well under a second.
Example 1
n = 00Example 2
n = 1055Example 3
n = 68Constraints
nis a whole number from 0 to 90.- The answer can be big (
fib(90)has 19 digits), but Python's whole numbers hold it exactly.
Submit also runs 4 more tests you can't see.
Practises Recursion (lesson 20).
- The plain recursion,
fib(n - 1) + fib(n - 2), works out the same numbers again and again:fib(90)would take trillions of calls. - Work forwards instead. You only ever need the last two numbers, so start with
a, b = 0, 1:fib(0)andfib(1). - Repeat
ntimes:a, b = b, a + b. Thenaisfib(n), and forn = 0the loop doesn't run, soastays 0. (Or keep the recursion and remember answers with@functools.lru_cache.)
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def fib(n):
"""Return the nth Fibonacci number, quickly.
n: int, from 0 to 90
Returns: int, where fib(0) is 0, fib(1) is 1, and each
next one is the sum of the two before it
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.