Python Class Fraction Numbers
I made a code that makes the user input two fraction numbers in the form 'd/n'. How can I make it print the reduced form of the fraction ? ex: when I type 2/4 it prints 1/2? i
Solution 1:
Use the fractions.Fraction()
class and have it do the work for you:
>>>import fractions>>>fractions.Fraction(2, 4)
Fraction(1, 2)
To simplify fractions yourself, calculate the greatest common divisor:
def gcd(a, b):
while b:
a, b = b, a%b
returnag= gcd(numerator, denominator)
numerator //= g
denominator //= g
Solution 2:
>>> num = 2
>>> den = 4
>>> from fractions import Fraction
>>> frac = Fraction(num,den).limit_denominator()
>>> numer = frac.numerator
>>> denom = frac.denominator
>>> print'%d/%d ~ %g' % (numer, denom, float(numer)/denom)
1/2 ~ 0.5
Hope this helps. (link http://docs.python.org/2/library/fractions.html)
Solution 3:
Simply divide the numerator
and the denominator
to their greatest common divisor before showing the number. That is if you want to use your own class. Otherwise there is a Fraction
class in the fractions
module.
Solution 4:
Well, first you're going to have to add support to your Rational
class that computes the reduced form for a fraction. Basically, what you need to do is add a reduce()
method that finds the lowest common denominator of the two numerator, denominator in the Rational. Try looking at Least Common Multiple for an algorithm.
Solution 5:
import fractions
f = fractions.Fraction(5, 10)
print (f) # print1/2
Post a Comment for "Python Class Fraction Numbers"