2

I am making a simple script in Python as an exercise that evaluates the Ackermann Function. First the script asks the user for an input, and then attempts to calculate the rest. Here is the code:

m = int(input('Please input m.\n'))
n = int(input('Please input n.\n'))


def compute(m, n):
    if m == 0:
        print(n + 1)
    elif m > 0 and n == 0:
        compute(m - 1, 1)
    else:
        compute(m - 1, compute(m, n - 1))


compute(m, n)

The part that has me confused is when it returns a TypeError, particularly for lines in compute(m, n) where I attempt to add or subtract 1 from n and m.

print(n + 1)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

I understand that Python takes all inputs as string, which is why I specifically converted the input using int() at the very start of the script. And yet, the TypeError seems to implicate that in compute(m, n), m and n are not int, but rather NoneType thus they cannot be added or subtracted. Why is this, and how can I fix this?

Community
  • 1
  • 1
Ymi
  • 609
  • 6
  • 18
  • 5
    `compute` is recursive, but doesn't explicitly return, meaning that `None` is always returned. – dspencer Mar 20 '20 at 08:00
  • 2
    Your function isn't returning a result. All it does is print `n+1` if `m` is zero. None of the recursive calls will work. – Tom Karzes Mar 20 '20 at 08:02
  • Python by default returns ```None``` . Recursion must have at least one stopping condition. Else, it will result to stackoverlow. – drd Mar 20 '20 at 08:11
  • Thank you for the comments, I understand now. – Ymi Mar 20 '20 at 08:16
  • Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – Tomerikoo Mar 20 '20 at 08:31

1 Answers1

6

Any fruitful recursive function must have one or more return statements. Refer this.

m = int(input('Please input m.\n'))
n = int(input('Please input n.\n'))

def compute(m, n):
    if m == 0:
        return n + 1
    elif m > 0 and n == 0:
        return compute(m - 1, 1)
    else:
        return compute(m - 1, compute(m, n - 1))


print(compute(m, n))

should work as you expect.

lifebalance
  • 1,846
  • 3
  • 25
  • 57
  • 2
    It would be better to explain what you actually changed and why it solves the problem instead of just putting a piece of code – Tomerikoo Mar 20 '20 at 08:30