May-20-2021, 12:31 PM
This is why using recursion shouldn't be taken for granted. The use of resources can easily become exponential; and the more resources are used per function call, the worse it'll be.
While recursion can provide a simpler and more readable solution to a problem, you'll be able to achieve similar results if you use the right tools. For instance, this code:
While recursion can provide a simpler and more readable solution to a problem, you'll be able to achieve similar results if you use the right tools. For instance, this code:
def fib(n): fibs = [] for i in range(n + 1): if i < 2: fibs.append(i) else: fibs.append(fibs[i - 2] + fibs[i - 1]) return fibs[-1] if n >= 0 else 0Provides the same simple solution by making use of a list to save and use the results as we iterate from 0 to n (included). The memory footprint in this case is minimal (only one function call and a list), as we don't take additional steps to keep track of n-1 and n-2 in order to calculate and use these.