1

I made a code that makes the user input two fraction numbers in the form "d/n".

How can I make it print the reduced form of the fraction ?

ex: when I type 2/4 it prints 1/2?

   import sys

class Rational:

  def __init__(self,n,d):
    self.numerator= n
    self.denominator= d
  def value(self):
    return float(self.numerator)/float(self.denominator)

  def __repr__(self):
    return "%d/%d ~ %g" % (self.numerator,self.denominator,self.value())
  def read(self):
    while 1:
      try:
        s=raw_input("Enter fraction n/d: ")
        n,d= s.split("/")
        self.numerator= int(n)
        self.denominator= int(d)
      except KeyboardInterrupt:
        print
        exit()
      except:
        print sys.exc_info()[0]
        print "bad input, try again."
      else:
        if int(d)==0:
          print "The denominator cannot be zero. Try again."
        elif int(d)<0:
          print "The denominator cannot be negative. Try again."
        else:
          return

r1=Rational(1,1)
r1.read()
print r1

r2=Rational(1,1)
r2.read()
print r2
rsp
  • 339
  • 2
  • 3
  • 9

5 Answers5

4

Use the fractions.Fraction() class and have it do the work for you:

>>> import fractions
>>> fractions.Fraction(2, 4)
Fraction(1, 2)

To simplify fractions yourself, calculate the greatest common divisor:

def gcd(a, b):
    while b:
        a, b = b, a%b
    return a

g = gcd(numerator, denominator)
numerator //= g
denominator //= g
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • may I ask you why the '//' instead of the single '/'?? – RGS Mar 07 '14 at 20:12
  • 1
    @RSerrao: floor division instead of float division (or, in Python 2, floor *or* float division depending on the operands). – Martijn Pieters Mar 07 '14 at 20:33
  • My point is, if you know that g is going to be a whole divisor of both num and den, why the floor division? Is it good practice or it doesn't matter? – RGS Mar 08 '14 at 01:06
  • 2
    Good practice, explicit is better than implicit, and most of all ensuring that int is returned; in Python 3 `/` *always* results in a `float` result; ditto for Python 2 if `from __future__ import division` was used. – Martijn Pieters Mar 08 '14 at 01:24
  • Ok, thank you. Looks like I'll have to change my Fraction class too :p – RGS Mar 08 '14 at 09:15
1
    >>> num = 2
    >>> den = 4        
    >>> from fractions import Fraction
    >>> frac = Fraction(num,den).limit_denominator()
    >>> numer = frac.numerator
    >>> denom = frac.denominator
    >>> print '%d/%d ~ %g' % (numer, denom, float(numer)/denom)
    1/2 ~ 0.5

Hope this helps. (link http://docs.python.org/2/library/fractions.html)

its me
  • 127
  • 2
  • 8
0

Simply divide the numerator and the denominator to their greatest common divisor before showing the number. That is if you want to use your own class. Otherwise there is a Fraction class in the fractions module.

Community
  • 1
  • 1
0

Well, first you're going to have to add support to your Rational class that computes the reduced form for a fraction. Basically, what you need to do is add a reduce() method that finds the lowest common denominator of the two numerator, denominator in the Rational. Try looking at Least Common Multiple for an algorithm.

jwir3
  • 6,019
  • 5
  • 47
  • 92
0
import fractions

f = fractions.Fraction(5, 10)
print (f) # print 1/2
JoeC
  • 1,850
  • 14
  • 12