I've searched similar questions about converting classes but none have really helped me.
I have a Fraction class and want to simplify it to an int if possible.
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.simplify()
if self.denominator == 1:
# convert self to int of value numerator
I have a function within the Fraction class which will simplify the fraction when it is created (2/6 becomes 1/3, etc.)
def simplify(self):
div = gcd(self.numerator, self.denominator)
self.numerator //= div
self.denominator //= div
My current solution to this problem is as follows:
def convert(fraction):
if fraction.denominator == 1:
return fraction.numerator # int
else:
return fraction # Fraction
f = Fraction(3, 1)
f = convert(f)
I'm using these fractions in various algebraic expressions so I would like them to be as simple as possible. eg. 1/2 + 1/2 = 1 (instead of 1/1)
Is there any way I can convert the Fraction object into an int without having to pass it through this external function every time?
Thanks
There are a couple of things you can do:
It is not optimal to have a function which returns two different types, so you could handle the conversion with a class method.
It would help if the conversion was supported in the print() func as well
With that in mind, I just moved convert inside the class, and added a str method as well.
from fractions import gcd
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.simplify()
def __str__(self):
if self.denominator == 1:
return str(self.numerator)
return '{}/{}'.format(self.numerator,self.denominator)
def simplify(self):
div = gcd(self.numerator, self.denominator)
self.numerator //= div
self.denominator //= div
def convert(fraction):
if fraction.denominator == 1:
return fraction.numerator # int
return fraction # Fraction
if __name__ == '__main__':
f = Fraction(6, 2)
c = Fraction.convert(f)
print(f)
print(c)
f2 = Fraction(3, 4)
print(f2)
See if it can help you.
Related
I'm trying to reduce(self) to return fractions which have the lowest value.
This is the code I have:
class fraction:
def __init__(self,numerator,denominator):
self.numerator = numerator
self.denominator = denominator
self.reduce()
def get_numerator(self):
return self.numerator
def get_denominator(self):
return self.denominator
def reduce(self):
pass
def __str__(self):
return str(self.numerator) + "/" + str(self.denominator)
And this is the test code:
# y = fraction(2*7,7*2)
# z = fraction(13,14)
# a = fraction(13*2*7,14)
# print(x)
# print(y)
# print(z)
# print(a)
I don't want to use math.gcd or import fractions but rather do it by hand.
I'm not sure what to try without these operators. Would it be perhaps a while loop?
You can implement reduce() using Greatest Common Divisor. As #NickODell said in comment this GCD algorithm is described in Euclidean Algorithm Wiki. And implemented in my code below:
Try it online!
class fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.reduce()
def get_numerator(self):
return self.numerator
def get_denominator(self):
return self.denominator
#staticmethod
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def reduce(self):
if self.numerator == 0 or self.denominator == 0:
return
g = self.gcd(self.numerator, self.denominator)
self.numerator //= g
self.denominator //= g
def __str__(self):
return str(self.numerator) + "/" + str(self.denominator)
y = fraction(2*7,7*2)
z = fraction(13,14)
a = fraction(13*2*7,14)
print(y)
print(z)
print(a)
print(fraction(15, 35))
Output:
1/1
13/14
13/1
3/7
I have written a code where I have defined a class Fraction. Throughout the code, all binary operations such as +, -, /, * can be performed. Now I would also like to be able to perform unary operations for the class Fraction such as abs() etc. However, this does not work at the moment, when performing for example the unary operation abs() I get a TypeError: bad operand type for abs (): 'Fraction'. Below is part of the code that deals purely with fraction subtraction, it is representative for the entire code:
def gcd(denominator, numerator):
if numerator == 0:
return denominator
else:
return gcd(numerator, (denominator % numerator))
class Fraction:
def __init__(self,numerator = 0, denominator = 1):
self.numerator = int(numerator / gcd(abs(denominator),abs(numerator) ))
self.denominator = int(denominator / gcd(abs(denominator),abs(numerator) ))
if self.denominator < 0:
self.denominator = abs(self.denominator)
self.numerator = -1*self.numerator
elif self.denominator == 0:
raise ZeroDivisionError
def __str__(self):
if self.denominator == 1:
return str(self.numerator)
else:
return str(self.numerator) + "/" + str(self.denominator)
def __neg__(self):
return Fraction(-self.numerator, self.denominator)
def __rsub__(self,other):
return self.__sub__(other)
def __sub__(self,other):
if type(other) == int:
other = Fraction(other,1)
return self.sub(other)
else:
return self.sub(other)
def sub(self,other):
result = Fraction()
result.numerator = other.denominator * self.numerator - self.denominator * other.numerator
result.denominator = other.denominator * self.denominator
multiple = gcd(result.denominator,result.numerator)
result.numerator = int(result.numerator / multiple)
result.denominator = int(result.denominator / multiple)
if result.denominator < 0:
result.denominator = abs(result.denominator)
result.numerator = 0 - result.numerator
return result
else:
return result
return result
p = Fraction(2,3)
q = Fraction(4,5)
r = (p - q)
What I would like is that when I give the statement print(abs(r)) the output is the fraction in absolute value. So in the example where p = Fraction(2,3), q = Fraction(4,5) and r = (p - q). Then the statement print(r) gives the output -2/15 and the statement print(abs(r)) gives the output 2/15. Or that for example print(float(r)) gives the output -0.133333333. However, I keep getting the previously mentioned TypeError.
I've been looking for a while, but so far I haven't been able to find a solution, do you know how I can fix this?
Thanks in advance!
As already mentioned in the comment implement __abs__ and __float__.
Add this to your class:
def __abs__(self):
return Fraction(abs(self.numerator), abs(self.denominator))
def __float__(self):
return self.numerator / self.denominator
Maybe
def __abs__(self):
return Fraction(abs(self.numerator), self.denominator)
would be already enough, when your denominator is always positive.
>>> p = Fraction(2, 3)
>>> q = Fraction(4, 5)
>>> r = p - q
>>> print(r)
-2/15
>>> print(abs(r))
2/15
>>> print(float(r))
-0.13333333333333333
In part of my code I can subtract fractions, however if I enter (- p) where p is a fraction I get a TypeError: unsupported operand type(s) for +: "Fraction" and "Fraction"
def gcd(denominator, numerator):
if numerator == 0:
return denominator
else:
return gcd(numerator, (denominator % numerator))
class Fraction:
def __init__(self,numerator = 0, denominator = 1):
self.numerator = int(numerator / gcd(abs(denominator),abs(numerator) ))
self.denominator = int(denominator / gcd(abs(denominator),abs(numerator) ))
if self.denominator < 0:
self.denominator = abs(self.denominator)
self.numerator = -1*self.numerator
elif self.denominator == 0:
raise ZeroDivisionError
def __str__(self):
if self.denominator == 1:
return str(self.numerator)
else:
return str(self.numerator) + "/" + str(self.denominator)
def __rsub__(self,other):
return self.__sub__(other)
def __sub__(self,other):
if type(other) == int:
other = Fraction(other,1)
return self.sub(other)
else:
return self.sub(other)
def sub(self,other):
result = Fraction()
result.numerator = other.denominator * self.numerator - self.denominator * other.numerator
result.denominator = other.denominator * self.denominator
multiple = gcd(result.denominator,result.numerator)
result.numerator = int(result.numerator / multiple)
result.denominator = int(result.denominator / multiple)
return result
p = Fraction(2,3)
r = (- p)
However, when my input is (1 - p) I get the correct output. Suppose p = Fraction(2, 3) then I would like (- p) to return (-2 / 3) or (2/ -3). The problem seems to me to be in the fact that no input is given for the first argument when subtracting. While searching I did come across things like __neg__, but I'm still new to python and using classes so I don't know exactly how to implement this. Does anyone know how I can fix this?
Thanks in advance!
You are right; you need to implement __neg__ because that minus is not the (binary) subtraction operator, but the unary minus.
Here is how you can do it:
def __neg__(self):
return Fraction(-self.numerator, self.denominator)
Other issues
__rsub__
You need to change the implementation of __rsub__, because that method will be called when other does not support __sub__. For instance, it will kick in when you evaluate this:
p = 1 - Fraction(2, 3)
That evaluation will not work as it currently stands. You need to have this:
def __rsub__(self, other):
return Fraction(other) - self
or, explicitly calling __sub__:
def __rsub__(self, other):
return Fraction(other).__sub__(self)
Normalising
The constructor correctly normalises the fraction, making sure the denominator is positive, but you don't do the same in the sub method. There the result may not be normalised: the denominator could remain negative.
Moreover, it is a pity that you duplicate the gcd-related code that is already in the constructor. It is better to rely on the constructor for that logic.
Immutability
It is better to treat instances as immutable. So you should not have any assignments to instance.numerator and instance.denominator outside of the constructor. Make sure to first determine the numerator and denominator (without normalisation), and then call the constructor passing these as arguments.
Comparisons
You may want to compare Fractions for equality or relative order. For that you can implement __eq__, __lt__, ...etc.
Proposed code
Here is how I would do it:
def gcd(denominator, numerator):
if numerator == 0:
return denominator
else:
return gcd(numerator, denominator % numerator)
class Fraction:
def __new__(cls, numerator=0, denominator=1):
if isinstance(numerator, Fraction):
return numerator # Use this instance and ignore 2nd argument
return super(Fraction, cls).__new__(cls)
def __init__(self, numerator=0, denominator=1):
if isinstance(numerator, Fraction):
return # self is already initialised by __new__
if denominator == 0:
raise ZeroDivisionError
div = gcd(abs(denominator), abs(numerator))
if denominator < 0:
div = -div
self.numerator = numerator // div
self.denominator = denominator // div
def __str__(self):
if self.denominator == 1:
return str(self.numerator)
else:
return f"{self.numerator}/{self.denominator}"
def __rsub__(self, other):
return Fraction(other) - self
def __sub__(self, other):
other = Fraction(other)
return Fraction(other.denominator * self.numerator
- self.denominator * other.numerator,
other.denominator * self.denominator)
def __neg__(self):
return Fraction(-self.numerator, self.denominator)
def __eq__(self, other):
other = Fraction(other)
return (self.numerator == other.numerator and
self.denominator == other.denominator)
def __lt__(self, other):
other = Fraction(other)
return (other.denominator * self.numerator <
self.denominator * other.numerator)
def __gt__(self, other):
return Fraction(other) < self
def __le__(self, other):
return self < other or self == other
def __ge__(self, other):
return self > other or self == other
Your __rsub__ code is flipped, you want other.__sub__(self).
def __rsub__(self,other):
return other.__sub__(self)
How do I create the divide method in Python?
This is my code:
# Rational numbers
def gcd(bigger, smaller):
'''compute the greatest common divisor of two positive integers'''
#print(' in gcd ')
if not bigger > smaller :
bigger, smaller = smaller, bigger
while smaller != 0:
remainder = bigger % smaller
#print('gcd calc, big:{}, small:{}, rem:{}'.format(bigger, smaller, remainder))
bigger, smaller = smaller, remainder
return bigger
def lcm(a, b):
'''calculate the least common multiple of two positive integers'''
#print(' in lcm ')
return (a*b)//gcd(a,b)
class Rational(object):
'''Rational with numerator and denominator. Denominator defaults to 1'''
def __init__(self, numer, denom = 1):
#print('in constructor')
self.numer = numer
self.denom = denom
def __str__(self):
'''String representation for printing'''
#print(' in str ')
return str(self.numer) + '/' + str(self.denom)
def __repr__(self):
''' Used in the interpreter. Call __str__ for now'''
print(' in repr ')
return self.__str__()
def __add__(self, param_Rational):
'''Add two Rationals'''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
# find the lcm
the_lcm = lcm(self.denom, param_Rational.denom)
# multiply each numerator by the lcm, then add
numerator_sum = the_lcm*self.numer/self.denom + \
the_lcm*param_Rational.numer/param_Rational.denom
return Rational( int(numerator_sum), the_lcm )
else:
print("Wrong type in addition method.")
raise(TypeError)
def __sub__(self, param_Rational):
'''Subtract two Rationals'''
#print(' in add ')
# find the lcm
the_lcm = lcm(self.denom, param_Rational.denom)
# multiply each numerator by the lcm, then add
numerator_sum = the_lcm*self.numer/self.denom - \
the_lcm*param_Rational.numer/param_Rational.denom
return Rational( int(numerator_sum), the_lcm )
def reduce_rational(self):
'''Return the reduced fraction value as a Rational'''
# find the gcd and divide numerator and denominator by it
the_gcd = gcd(self.numer, self.denom)
return Rational( self.numer//the_gcd, self.denom//the_gcd)
def __eq__(self, param_Rational):
'''Compare two Rationals for equalit and return a Boolean'''
reduced_self = self.reduce_rational()
reduced_param = param_Rational.reduce_rational()
return reduced_self.numer == reduced_param.numer and\
reduced_self.denom == reduced_param.denom
def __mul__(self, param_Rational):
''' Multiply two Rationals '''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
#multiply
denom_zero_check = self.denom
second_denom_zero_check = param_Rational.denom
if denom_zero_check & second_denom_zero_check > 0:
numer_mul = self.numer*param_Rational.numer
denom_mul = self.denom*param_Rational.denom
return Rational(int(numer_mul),int(denom_mul))
else:
print("Denominator can't be zero.")
else:
print("Wrong type in subtraction method")
raise(TypeError)
""" """
def __truediv__(self): # <-------- Here is where TypeError occurs #
''' Divide two Rationals '''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
#multiply
denom_zero_check = self.denom
second_denom_zero_check = param_Rational.denom
if denom_zero_check & second_denom_zero_check > 0:
numer_mul = self.numer*param_Rational.denom
denom_mul = self.denom*param_Rational.numer
return Rational(int(numer_mul),int(denom_mul))
else:
print("Denominator can't be zero.")
And I'm getting the error (location marked above):
TypeError: __truediv__() takes 1 positional argument but 2 were given
How do I fix this? I got the multiplication down but not the divide, should I use div or truediv? And do I need to use / in the actual div method?
How can __truediv__ only take one argument? You need two, self and the divisor. The same way your __mul__ __add__, and __sub__ needed a second argument.
def __truediv__(self, param_Rational):
# rest of your code
Instead of first printing an error message and then raising the error, you can use:
raise TypeError("Wrong type in addition method.")
Also, it might be usefull to check wether the demnominator is 0 or not in init(), and raise ZeroDivisionError if it is.
PS: 2/3 / 6/9 should equal 1/1 as 2/3=6/9=0.666...
I'm new to Python,
After initialising an instance f of class Fraction, I want the method reduce has been invoked, so the print result is after reduced
f = Fraction(3,6)
print f #=> 1/2 not 3/6
here's the code:
class Fraction(object):
'''Define a fraction type'''
def __init__(self, num=0, denom=1):
'''Create a new Fraction with numerator num and denominator demon'''
self.numerator = num
if denom != 0:
self.denominator = denom
else:
raise ZeroDivisionError
def reduce(self):
gcd = findgcd(self.numerator, self.denominator)
self.numerator /= gcd
self.denominator /= gcd
def findgcd(self, x, y):
gcd = None
min_number = min(x, y)
for i in range(min_number, 1, -1):
if x % i == 0 and y % i == 0:
gcd = i
return gcd
def __repr__(self):
return "{0}/{1}".format(self.numerator, self.denominator)
What prevent you from calling self.reduce() at the end of __init__ method?
You have two problems:
you need to call self.reduce() in your constructor __init__ to have method reduce() invoked during the instantiation phase.
you also need to change:
def reduce(self):
gcd = findgcd(self.numerator, self.denominator)
to:
def reduce(self):
gcd = self.findgcd(self.numerator, self.denominator)
because otherwise your instance will not be able to find findgcd.
The following code will fix your problem:
class Fraction(object):
'''Define a fraction type'''
def __init__(self, num=0, denom=1):
'''Create a new Fraction with numerator num and denominator demon'''
self.numerator = num
if denom != 0:
self.denominator = denom
else:
raise ZeroDivisionError
self.reduce()
def reduce(self):
gcd = self.findgcd(self.numerator, self.denominator)
self.numerator /= gcd
self.denominator /= gcd
def findgcd(self, x, y):
gcd = None
min_number = min(x, y)
for i in range(min_number, 1, -1):
if x % i == 0 and y % i == 0:
gcd = i
return gcd
def __repr__(self):
return "{0}/{1}".format(self.numerator, self.denominator)
>>>> f = Fraction(3,6)
>>>> f
1/2