bisera
bisera

Reputation: 1

How to get the nominator/denominator of a Fraction object

I have four variables that are added as fractions:

n1 = input("Denominator 1")
d1 = input("Denominator 1")
n2 = input("Denominator 1")
d2 = input("Denominator 1")

def fraction(n1,d1,n2,d2):
    a = Fraction(n1,d1)
    b = Fraction(n2,d2)
    print(a+b)
    return

fraction(n1,d1,n2,d2)

The answer comes out as something like 23/45.

How would I separate the two numbers and remove the divisor?

23
---
45

Upvotes: 0

Views: 1423

Answers (2)

berdario
berdario

Reputation: 1860

a = Fraction(n1, d1)
b = Fraction(n2, d2)
c = a+b
print(c.numerator, c.denominator, sep="\n---\n")

The next time that you'll need something like this, do dir(c)

you'll get back something like:

 [..., '_sub', 'conjugate', 'denominator', 'from_decimal', 'from_float', 'imag', 'limit_denominator', 'numerator', 'real']

(also, help(c) or looking at the documentation is useful)

Upvotes: 2

Steinar Lima
Steinar Lima

Reputation: 7821

Use Fraction.numerator and Fraction.denominator:

>>> from fractions import Fraction
>>> a = Fraction(1, 2)
>>> b = Fraction(2, 3)
>>> tot = a+b
>>> print(tot, tot.numerator, tot.denominator)
7/6 7 6

Upvotes: 2

Related Questions