One last example
Before we finish this chapter, I'll show you a simple problem that I used to submit to candidates for a Python developer role in a company I used to work for.
The problem is the following: given the sequence 0 1 1 2 3 5 8 13 21 ...
, write a function that would return the terms of this sequence up to some limit, N
.
If you haven't recognized it, that is the Fibonacci sequence, which is defined as F(0) = 0, F(1) = 1 and, for any n > 1, F(n) = F(n-1) + F(n-2). This sequence is excellent to test knowledge about recursion, memoization techniques, and other technical details, but in this case, it was a good opportunity to check whether the candidate knew about generators.
Let's start from a rudimentary version of a function, and then improve on it:
# fibonacci.first.py def fibonacci(N): """Return all fibonacci numbers up to N. """ result = [0] next_n = 1 while next_n <= N: result.append(next_n) next_n = sum(result[-2:]) return result print...