Displaying full Fractions result

0

I'm generating number simplifications through the Fractions package.

All right until you find numbers where the simplification goes to the maximum, ie reducing one of the terms to "1".

When this happens, the program skips this value, displaying only the other value. For example:

import fractions as F
print(F.Fraction(723520/51680))

It will output 14 and not 14/1 as it should be and like the package's own documentation shows which was to occur. Example Fraction(123) of the documentation.

IdeOne link

    
asked by anonymous 27.02.2018 / 02:44

1 answer

2

The documentation examples display the results directly from the Python interactive terminal and they display object representation, that is, the return of the __repr__ method through the repr() function. So to achieve the same result, you will have to do:

print(repr(Fraction(723520/51680)))

This is because the print() function internally invokes the __str__ method of the object, which produces the scalar result, 14. If you want to access the numerator and denominator values as integers, simply access the numerator and denominator fields % of object Fraction , respectively. Here's an example:

from fractions import Fraction

f = Fraction(723520/51680)

print('str(f) =', f)
print('repr(f) =', repr(f))

# Acessando numerador e denominador

print('Numerador:', f.numerator)
print('Denominador:', f.denominator)

See working at Repl.it | Ideone

Official documentation: 9.5. fractions - Rational numbers

    
27.02.2018 / 02:53