# [Tutor] Fraction Class HELP ME PLEASE!

Quiles, Stephanie stephanie.quiles001 at albright.edu
Thu Aug 6 18:55:22 CEST 2015

```Hello All,

I need to do the following assignment. I need to know how do i hard code an example for each of the operators I am implementing? What i have so far is below? He said he does not care if we plug in some numbers or if we have user input numbers, however I am unsure of how to write a program that tests each operator? Or can i write one that tests all of them? I don’t know where to start with this. Please help!

We discussed implementing different operators in our Fraction class. Here is a link to some operators in Python (look at Section 10.3.1). https://docs.python.org/3/library/operator.html

You may implement as many of these operators as you like (such as isub, itruediv, etc.) You MUST indicate in your header information which operators you are implementing, and you MUST hard code an example for each.

def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n

m = oldn
n = oldm % oldn
return n

class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom

def __str__(self):
if self.den == 1:
return str(self.num)
elif self.num == 0:
return str(0)
else:
return str(self.num) + "/" + str(self.den)

def simplify(self):
common = gcd(self.num, self.den)

self.num = self.num // common
self.den = self.den // common`

def show(self):
print(self.num, "/", self.den)

newnum = self.num * otherfraction.den + \
self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __sub__(self, otherfraction):
newnum = self.num * otherfraction.den - \
self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __mul__(self, otherfraction):
newnum = self.num * otherfraction.num * \
self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __imul__(self, otherfraction):
if isinstance(otherfraction):
return self__mul__(otherfraction)

if isinstance(otherfraction):

def __truediv__(self, otherfraction):
newnum = self.num * otherfraction.num // self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

newnum = self.num * otherfraction.num // self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def getNum(self):
return self.num

def getDen(self):
return self.den

def __gt__(self, otherfraction):
return (self.num / self.den) > (otherfraction.num / otherfraction.den)

```