4 ms·
Further reading about the relationship between recursion, iteration, and accumulators: https://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html htt
by b3morales 5y ago
Further reading about the relationship between recursion, iteration, and accumulators: https://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html https://blog.moertel.com/posts/2013-05-11-recursive-to-itera...
This transformation is one you can apply in your own source as well. An example from that link, the recursive
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
can be rewritten iteratively:
def factorial1d(n, acc=1):
while n > 1:
(n, acc) = (n - 1, acc * n)
return acc