Another interesting approach using iteration is making the function into a generator which can be used as part of for loops, list comprehensions, etc
defgen_fib():a,b=1,1yieldayieldbwhileTrue:a,b=b,a+byieldbg=gen_fib()# Generate the first 200,000 Fibonacci numbers
fibs=[next(g)for_inrange(200000)]
I am generally wary of writing code using pure recursion in Python as it can easily blow the stack due to recursion limit. For example if we try to solve using recursion as:
deffib(n):ifn<=1:return1returnfib(n-2)+fib(n-1)
This takes exponential time because it recalculates fib(n-2) for fib(n-1).
If we try to make it linear time using functools.lru_cache which will cache the previous calls at cost of O(n) memory, this still gives maximum recursion depth exceeded in comparison error for fib(200000).
All the best for the interview!
Another interesting approach using iteration is making the function into a generator which can be used as part of for loops, list comprehensions, etc
I am generally wary of writing code using pure recursion in Python as it can easily blow the stack due to recursion limit. For example if we try to solve using recursion as:
This takes exponential time because it recalculates
fib(n-2)
forfib(n-1)
.If we try to make it linear time using
functools.lru_cache
which will cache the previous calls at cost of O(n) memory, this still givesmaximum recursion depth exceeded in comparison
error for fib(200000).if Tail call optimization was supported in Python, the following recursive variant will be "optimized" to iterative version:
But due to no TCO, it still results in same
maximum recursion depth exceeded in comparison
forfib_tail(200000)