[Tutor] Re: help for code from instant hacking

Max M. Stalnaker stalnaker@acm.org
Wed, 18 Aug 1999 23:26:00 -0700


I would guess the reason it is hard to visualize is that it involves
*recursion*

def func(a,b):
    #manipulations of a,b
    if b=0 return a
    else return func(a,b)

print func(a,b)

I believe this is called tail-recursion, a special case of recursion.

Recursion pushes successive execution frames onto a stack.  Eventually it
completes.
At that time it returns a.  The value of the a migrates up the stack and
eventually is printed.  All the stack stuff is handled by the language
transparently, but if you need to visualize what is happening, I think you
need to visual the execution frames on the stack.

Feel free to draw pictures of the execution frames.   These hold the state of
one level of recursion of func(a,b).

tutor-admin@python.org wrote:

> Subject: [Tutor] Help with the code for an exercise in, "Instant Hacking"
> Date: Wed, 18 Aug 1999 21:42:06 -0400
> From: "Dempsey" <infody@earthlink.net>
> To: <tutor@python.org>
>
> The following exercise is found in the, "Instant
> Hacking".
>
> I'm having trouble visualizing this exercise shown
> below.  Could someone show me what the code would
> look like?
>
> Thanks,
>
> Bob
> infody@earthlink.net
> --------------------------------------------------
> ---------------
>
> Exercise 2
> Write a function that implements Euklid's method
> for finding a common factor of two numbers. It
> works like this:
> You have two numbers, a and b, where a is larger
> than b
> You repeat the following until b becomes zero:
> a is changed to the value of b
> b is changed to the remainder when a (before the
> change) is divided by b (before the change)
> You then return the last value of a
> Hints:
> *       Use a and b as parameters to the function
> *       Simply assume that a is greater than b
> *       The remainder when x is divided by z is
> calculated by the expression x % z
> *       Two variables can be assigned to simultaneously
> like this: x, y = y, y+1. Here x is given the
> value of y (that is, the value y had before the
> assignment) and y is incremented by one
>
>   ------------------------------------------------------------------------
>                   Name: winmail.dat
>    winmail.dat    Type: application/ms-tnef
>               Encoding: base64
>
>   ------------------------------------------------------------------------
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor

--
Max M. Stalnaker mailto:stalnaker@acm.org http://www.astarcc.com
253-565-2366 fax 253-565-0892