Di-lemma
Di-lemma

Reputation: 113

Simplify output rationals python3

I've written a program that reads 2 fractions and an operator and gives me the answer when evaluated. Don't mind the length of the code, I just added it to be complete. My question is the following: when I enter as input

12/23
23/12
*

I want it to give me the output 1. However it gives me 1/1. How can I correct this?

x = input().split('/')
y = input().split('/')
z = input()
def gcd ( a, b ):
    if  b == 0:
        return a
    else:
        return gcd(b, a%b)

class Rational:
    def __init__ ( self, a=0, b=1 ):
        g  =  gcd ( a, b )
        self.n  =  a / g
        self.d  =  b / g
    def __add__ ( self, other ):
        return Rational ( self.n * other.d + other.n * self.d,
                          self.d * other.d )
    def __sub__ ( self, other ):
        return Rational ( self.n * other.d - other.n * self.d,
                          self.d * other.d )
    def __mul__ ( self, other ):
        return  Rational ( self.n * other.n, self.d * other.d )
    def __div__ ( self, other ):
        return  Rational ( self.n * other.d, self.d * other.n )
    def __str__ ( self ):
        return "%d/%d" % ( self.n, self.d )
    def __float__ ( self ):
        return  float ( self.n ) / float ( self.d )

q = Rational()
w = Rational()
q.n = int(x[0])
q.d = int(x[1])
w.n = int(y[0])
w.d = int(y[1])
answer = eval("q"+z+"w")

Upvotes: 1

Views: 58

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114588

Since it does not matter how you store the two equal numbers internally, the only method you need to modify is __str__, which does the external representation:

def __str__ ( self ):
    if self.d == 1:
        return "%d" % self.n
    return "%d/%d" % ( self.n, self.d )

This will handle all cases of n / 1 correctly, including 1 / 1.

Upvotes: 1

Related Questions