Question

I want to make a function that returns two values. The first should be the output of the ackerman function, and the second should be the number of times the function is called.

I've made the Ack function:

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

I tried making a global count and adding it before the if and elifs and return it with the answer:

global count
count +=1

if m == 0:
    return n+1, count

This is obviously wrong. It will return the count every time m = 0, and it would be a tuple.

How can I make it so that it returns a list of the answer of (for example) ack(3,4), which should be 125, and the number of times it had to call ack(m,n). So if I call ack(1.0,0.0) it should return [2.0, 2]. I need a list because I need to make some calculations with that sum.

The reason I need to know is because of an assignment out teacher gave us and I am completely stuck.

Was it helpful?

Solution

Just add 1 each time you recurse:

def ack(m,n):
    if m == 0:
        return (n + 1, 1)
    elif m > 0 and n == 0:
        a, cnt = ack(m - 1.0, 1.0)
        return a, cnt+1
    elif m > 0 and n > 0:
        a1, cnt1 = ack(m, n - 1.0)
        a2, cnt2 = ack(m - 1.0, a1)
        return a2, 1 + cnt1 + cnt2



>>> ack(3, 4)
    (125.0, 10307)
>>> ack(1, 0)
    (2.0, 2)

OTHER TIPS

Just add a count and increment each call:

def ack(m,n):
    if m == 0:
        return n + 1, 1
    elif m > 0 and n == 0:
        res, count = ack(m - 1, 1)
        return res, count + 1
    elif m > 0 and n > 0:
        t, tc = ack(m, n - 1)
        res, rc = ack(m - 1, t)
        return res, tc + rc + 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top