[Tutor] finding factorials

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon Jun 30 13:06:01 2003


On Mon, 30 Jun 2003, Payal Rathod wrote:

> Hi,
> I am very new to python and programming in general. I was reading a
> tutorial "Programming in Python" in which the author has asked the
> reader an problem which I am unable to get.
>
> Problem is as follow,
> Write  a function that implements Euclid's method for finding a common
>    factor of two numbers. It works like this:
>     1. You have two numbers, a and b, where a is larger than b
>     2. You repeat the following until b becomes zero:
>          1. a is changed to the value of b
>          2. b  is  changed to the remainder when a (before the change) is
>             divided by b (before the change)
>     3. You then return the last value of a
>
> My very basic solution is going totally wrong,


Hi Payal:


You have a small bug when you call euclid() recursively: it needs to
"return" that final value.  That is, instead of:


###
        if b != 0:
                euclid(a,b)
        return a
###


Try:


###
        if b != 0:
                return euclid(a,b)
        else:
                return a
###



This should work better because we're telling the system, "The return
value of euclid() is the return value when we call euclid() on that
smaller pair of numbers."


Otherwise, Python just drops the result on the floor.  The example below:

###
>>> def broken_square(x):
...     x * x
...
>>> broken_square(42)
>>> def real_square(x):
...     return x * x
...
>>> real_square(42)
1764
###


shows that the system behaves differently if we forget to add a 'return'
in there.  broken_square() here isn't doing anything for the same reasons
as your euclid() example.



Hope this helps!