I’m trying to write this code that prints a unit fraction when given a number(s). For instance UnitFraction(3) returns 1/3. This is fine however when I try to check for equivalence, I’m having trouble getting the right answer UnitFraction(2) == UnitFraction(3,6) should be True but I’m getting false. Any help?
class UnitFraction:
def __init__(self, numerator=1, denominator=1):
self.num = numerator
self.den = denominator
self.val = denominator/numerator
if math.gcd(self.num, self.den) != 1:
gcdt = math.gcd(self.num, self.den)
self.num = int(self.num/gcdt)
self.den = int(self.den/gcdt)
elif self.den == 0:
raise ZeroDivisionError('division by zero')
elif self.den < 0:
self.den = self.den*-1
self.num = self.num*-1
def __repr__(self):
if self.den == 1:
return str(self.num)
else:
return (f'{self.num}/{self.den}')
def __eq__(self, other):
return self.val == other.val
def __add__(self, other):
den1 = self.den
den2 = other.den
newdem = self.den*other.den
return Fraction((self.den*other.num)+(other.den*self.num), newdem)
def __sub__(self, other):
den1 = self.den
den2 = other.den
newdem = self.den*other.den
return Fraction(-(self.den*other.num)+(other.den*self.num), newdem)
def __mul__(self, other):
return Fraction((self.num*other.num), (self.den*other.den))
def __truediv__(self, other):
newnum = self.num * other.den
newnden = self.den * other.num
return(Fraction(newnum, newnden))
def plot(self):
border_pts = np.array([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])
xcoords = border_pts[:, 0]
ycoords = border_pts[:, 1]
remainder = self.num % self.den
for i in range(5):
plt.plot(xcoords+i, ycoords, 'black')
plt.axis('off')
plt.axis('equal')
plt.fill(xcoords*remainder, ycoords, color='blue')
UnitFraction(2) == UnitFraction(2,4)
>Solution :
Use the *args syntax to capture all of the arguments to __init__, then choose from there:
class UnitFraction:
def __init__(self, num, *args):
if(len(args) == 0):
self.numerator = 1
self.denominator = num
elif(len(args) == 1):
self.numerator = num
self.denominator = args[0]
else
raise "UnitFraction only takes 1 or 2 arguments"
It allows you to have a variable number of arguments, without losing the protection from multiple parameters being passed.