[Tutor] help with a recursive function

Mac Ryan quasipedia at gmail.com
Tue Sep 27 22:22:10 CEST 2011


On Tue, 27 Sep 2011 14:32:00 -0400
c smith <illusiontechniques at gmail.com> wrote:

> hi list,
> i understand the general idea of recursion and if I am following well
> written code I can understand how it works, but when I try to write
> it for myself I get a bit confused with the flow.
> I was trying to turn an ackerman function into python code for
> practice and I tried writing it like this:
> #!/usr/bin/env python
> 
> import sys, os
> def ack(m,n):
> 
>     if m == 0:
>         return n+1
>     elif m > 0 and n == 0:
>         ack(m-1,1)
>     elif m > 0 and n > 0:
>         ack(m-1,ack(m,n-1))
> 
> if __name__=='__main__':
>     sys.argv[1] = int(sys.argv[1])
>     sys.argv[2] = int(sys.argv[2])
> 
>     print ack(sys.argv[1], sys.argv[2])
> 
> The major problem, I think, is that I cant figure out where to turn
> the args into ints.

You did it right, just when you loaded them. What is not correct is to
try to assign them to a property inside a standard library module. You
should assign them to local variables (``m`` and ``n`` for example).

> Also, does the second 'elif' make sense?

I have am not familiar with the ackerman functions, but since you
mentioned recursion, I suppose you wanted to recurse in those elif`s
and return the result of a new call to the funtion.

If that is the case, you could happily skip the "else" part of "elif"
because if the ``if`` code will run, the interpreter will never reach
the ``elif`` line.

> I am not sure if the function can take itself as an argument.
> thanks for any suggestions, this list has been a big help.

Here's the code readapted (but verify it still does what is intended
to!):

#!/usr/bin/env python

import sys, os
def ack(m,n):

    if m == 0:
        return n+1
    if m > 0:
        if n == 0:
            return ack(m-1,1)
        if n > 0:
            return ack(m-1,ack(m,n-1))
    raise BaseException('Something is wrong here!')

if __name__=='__main__':
    m = int(sys.argv[1])
    n = int(sys.argv[2])
    print ack(m, n)


HTH!
/mac


More information about the Tutor mailing list