# Ackermann function without recursive function calls, in Python

**URL:** <https://discuss.python.org/t/ackermann-function-without-recursive-function-calls-in-python/7026>\
**Category:** Python Help\
**Created:** [February 4, 2021, 2:21pm UTC](https://discuss.python.org/t/ackermann-function-without-recursive-function-calls-in-python/7026 "2021-02-04T14:21:39Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Paddy3118](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/paddy3118/32/1396_2.png) [@Paddy3118](https://discuss.python.org/u/Paddy3118)\
**Post date:** [February 4, 2021, 2:21pm UTC](https://discuss.python.org/t/ackermann-function-without-recursive-function-calls-in-python/7026/1 "2021-02-04T14:21:39Z")

</div>

Someone on reddit said that you could write Ackermanns function iteratively and gave a [reference](https://www.researchgate.net/publication/2726659_Iterative_Procedures_for_Computing_Ackerman's_Function).(pdf). It turns out that the results all either replace recursive function calls with stacks, or with the use of arrays as stacks. Stacks are how recursive calls are made behind the scenes.

Having seen the papers examples, I took the idea of a stack and ran with it then plonked the result on [Rosetta Code.](http://rosettacode.org/wiki/Ackermann_function#Python:_Without_recursive_function_calls).

Here’s a copy of my initial version without optimisations on m. (The RC version has those optimisations and computes the _practically computable_ values quickly).

```python
from collections import deque

def ack_i(m, n):
    "Paddy3118's iterative"

    stack = deque([])
    stack.extend([m, n])

    while len(stack) > 1:
        n, m = stack.pop(), stack.pop()

        if m == 0:
            stack.append(n + 1)
        elif n == 0:
            stack.extend([m-1, 1])
        else:
            stack.extend([m-1, m, n-1])

    return stack[0]

"""
In [16]: %time ack_i(4, 1)
Wall time: 48min 45s
Out[16]: 65533

In [17]:
"""

```

.
