[Tutor] A small math puzzle [recreational Python]

Michael P. Reilly arcege@speakeasy.net
Sat, 5 Jan 2002 15:04:47 -0500


On Sat, Jan 05, 2002 at 08:25:10AM -0800, Kirby Urner wrote:

And for people using versions of Python out there in the real world...

>     class F:
> 
>         def __init__(self,numer,denom):
>            # reduce inputs to lowest terms
>            gcd = self.gcd(numer,denom)
>            self.num = numer//gcd
>            self.den = denom//gcd

             self.num = int(numer / gcd)
             self.den = int(denom / gcd)

>         def __add__(self,other):
>             # find lowest common multiple
>             a,b = self.num, other.num
>             comden = self.lcm(self.den, other.den)
>             if comden != self.den:
>                a *= comden//self.den

                 a = a * int(comdem / self.den)

>             if comden != other.den:
>                b *= comden//other.den

                 b = b * int(comdem / other.den)

>             return F(a+b,comden)
> 
>         def __sub__(self,other):
>             return self + (-other)
> 
>         def __neg__(self):
>             return F(-self.num,self.den)
> 
>         def gcd(self,a,b):
>             # find greatest common divisor of a,b
>             if b==0: return a
>             else: return self.gcd(b,a%b)
> 
>         def lcm(self,a,b):
>             # find lowest common multiple of a,b
>             return a*b//self.gcd(a,b)

              return int(a * b / self.gcd(a,b))

>         def __repr__(self):
>             # represent as (a/b)
>             return "(%s/%s)" % (self.num, self.den)
> 
>   >>> m  = F(1,2)
>   >>> n  = F(2,3)
>   >>> n+m
>   (7/6)
>   >>> n-m
>   (1/6)	

Make sure that you have the proper use of operators - this is a list
for people learning Python, and not all people can use Python 2.2 (which
adds the '//' operator and Python 2.0 which adds the '*=' operator).

If you are going to add code that will break when a newbie tries to
put it into a file and run it, make sure that you say which version you
are using.

  -Arcege