For more information on concepts covered in this lesson, you can check out Python Inner Functions: What Are They Good For?.
Using Iteration and a Python Function
00:00 Using Iteration and a Python Function. The example seen previously implements a recursive solution that uses memoization as an optimization strategy. In this section, you’ll code a function that uses iteration. The code seen next on-screen implements an iterative version of your Fibonacci sequence algorithm.
Lines 11 and 12 handle the base cases where
n is either
1. Line 14 defines two local variables,
fib_number, and initializes them with the first two numbers in the Fibonacci sequence.
This implementation of
fibonacci_of() is quite minimal. It uses iterable unpacking to compute the Fibonacci numbers during the loops, which is quite efficient memory-wise. However, every time you call the function with a different value of
n, it needs to recompute the sequence entirely.
02:25 One possible solution for this would be to make use of closures and make the function remember the already-computed values between calls. You can learn more about this in this Real Python course.
Become a Member to join the conversation.