Displaying full Fractions result

Asked

Viewed 45 times

0

I am 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 omits this value, displaying only the other one. For example:

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

Will generate the output 14 and not 14/1 how it should be and how the own documentation of the package shows that it was to occur. Example Fraction(123) of documentation.


link on Ideone

1 answer

2


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

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

That’s because the function print() invokes the method internally __str__ of the object, which produces the scalar result, 14. If you want to access the numerator and denominator values as integers, just access the fields numerator and denominator of the object Fraction, respectively. See 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 on Repl.it | Ideone

Official documentation: 9.5. Fractions - Rational Numbers

  • Thank you, Anderson. The result is generated as a type list, Right? In this case I needed to split and then strip to show only the numbers. It worked, but it didn’t get very Pythônico. No way to generate them in int? Thanks again

  • 1

    @Max No, the result is a string. There’s a much easier way that I’ve added to the answer to access the numerator and denominator values as integers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.