Tutorial: Simulating recursion with a stack

Revision en1, by ebanner, 2016-12-10 20:46:16

This will be a tutorial on simulating recursion with a stack. This approach assumes a linear chain of recursion calls found in functions like factorial(), as opposed to "branching" recursion which results in functions such as naive O(a^n) implementations of fibonnaci(), though I believe this approach can be extended to such cases. I developed this tutorial after using this technique to solve 472B - Уроки дизайна задач: учимся у жизни.

Consider the following recursive definition of the factorial() function:

def factorial(n):
   return n*factorial(n-1) if n > 1 else 1

This implementation should be familiar to anyone with experience with recursion, as it is often used as a basic example.

For reasons that will soon become clear, notice we can equivalently write this function as follows:

def factorial(n):
    if n == 1:
        return 1

    k = factorial(n-1)
    fact = n * k

    return fact

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en11 English ebanner 2018-04-21 07:11:59 105 (published)
en10 English ebanner 2018-04-21 07:07:07 652
en9 English ebanner 2018-04-21 07:02:18 1255
en8 English ebanner 2018-04-21 06:34:15 10
en7 English ebanner 2018-04-21 06:30:39 2049
en6 English ebanner 2016-12-10 22:52:18 135
en5 English ebanner 2016-12-10 22:50:48 1037 Tiny change: '3q8/pub?w=589&h=173)\n\nHere,' -
en4 English ebanner 2016-12-10 21:54:29 452 Tiny change: 'result by 3. Since we' -
en3 English ebanner 2016-12-10 21:42:57 1168 Tiny change: 'd84/pub?w=475&h=142)' -
en2 English ebanner 2016-12-10 21:04:46 760 Tiny change: ' = n * k\n\n ' -
en1 English ebanner 2016-12-10 20:46:16 967 Initial revision (saved to drafts)