Cruise5
Cruise5

Reputation: 247

Getting a TypeError on ackermann function. Not sure why

def ackermann(m, n):
    if m == 0:
        return n+1
    if n == 0:
        return (m-1,1)
    else:
        return ackermann(m-1,ackermann(m,n-1))

ackermann(10,5)

Getting TypeError:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print(ackermann(3,4))
  File "main.py", line 9, in ackermann
    return ackermann(m-1,ackermann(m,n-1))
  File "main.py", line 9, in ackermann
    return ackermann(m-1,ackermann(m,n-1))
  File "main.py", line 9, in ackermann
    return ackermann(m-1,ackermann(m,n-1))
  [Previous line repeated 2 more times]
TypeError: unsupported operand type(s) for -: 'tuple' and 'int'

I tried to visualize this on pythontutor.com and once m is 9, n is returning tuple (9,1) and the error starts.

Upvotes: 1

Views: 62

Answers (1)

Mureinik
Mureinik

Reputation: 311518

When n is 0 you return a tuple instead of calling ackermann:

def ackermann(m, n):
    if m == 0:
        return n+1
    if n == 0:
        return ackermann(m-1,1)
        # Here-^
    else:
        return ackermann(m-1,ackermann(m,n-1))

Upvotes: 2

Related Questions