Fractions

this adds,subtracts,multiplies,divides fractions and returns the fraction

class Fraction: '''represents fractions''' def __init__(self,num,denom): self.num=num self.denom=denom '''Fraction(num,denom) -> Fraction creates the fraction object representing num/denom''' if denom == 0: # raise an error if the denominator is zero raise ZeroDivisionError def __str__(self): lst=[] if self.num == 0: return "0" if self.num<0: neg=-self.num for i in range(1,neg+1): if self.num/i==self.num//i and self.denom/i==self.denom//i: lst.append(-1*i) minimum=min(lst) smplfiednum=self.num//minimum smplfieddenom=self.denom//minimum return str(smplfiednum)+'/'+str(smplfieddenom) elif self.num>0: for n in range(1,self.num+1): if self.num/n==self.num//n and self.denom/n==self.denom//n: lst.append(n) maximum=max(lst) smplfiednum=self.num//maximum smplfieddenom=self.denom//maximum return str(smplfiednum)+'/'+str(smplfieddenom) def __float__(self): return self.num/self.denom def add(self, other): newdenom = self.denom*other.denom newnum = (self.num*other.denom)+(other.num*self.denom) #self.denom=newdenom #self.num=newnum return Fraction(newnum, newdenom) def sub(self, other): newdenom = self.denom*other.denom newnum = (self.num*other.denom)-(other.num*self.denom) #self.denom=newdenom #self.num=newnum return Fraction(newnum,newdenom) def mul(self, other): newdenom = self.denom*other.denom newnum = self.num*other.num #self.denom=newdenom #self.num=newnum return Fraction(newnum,newdenom) def div(self, other): newdenom = self.denom*other.num newnum = self.num*other.denom #self.denom=newdenom #self.num=newnum return Fraction(newnum,newdenom) def eq(self,other): if self.denom/other.denom==self.num/other.num: return True else: return False # examples #getting p p = Fraction(3,6) print(p) # should print 1/2 q = Fraction(10,-60) print(q) # should print -1/6 r = Fraction(-24,-48) print(r) # should also print 1/2 x=float(p) print(x) # should print 0.5 ### if implementing "normal" arithmetic methods print(p.add(q)) # should print 1/3, since 1/2 + (-1/6) = 1/3 print(p.sub(q)) # should print 2/3, since 1/2 - (-1/6) = 2/3 print(p.sub(p)) # should print 0/1, since p-p is 0 print(p.mul(q)) # should print -1/12 print(p.div(q)) # should print -3/1 print(p.eq(r)) # should print True print(p.eq(q)) # should print False
1