Exercise: Fibonacci closure

Time to use a closure for real, the same exercise A Tour of Go uses.

The Fibonacci numbers start 0, 1 and each next number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, ...

Exercise: write fibonacci, which returns a function. Each time you call that function, it returns the next Fibonacci number, starting at 0.

  • Keep the two most recent numbers in the outer function, and update them with nonlocal.
  • Each call to fibonacci() must start its own sequence. Two sequences must not affect each other.
  • Each call should do a constant amount of work. Don't recompute the sequence from the start every time.

Tuple assignment helps here: a, b = b, a + b updates both at once.

Press Check to run the tests.