Student
Student

Reputation: 1197

How to work around Python object that does not support indexing?

Objective: to have two elements that can be called later in a script

Description: In the example below, I am only interested in the 0.25 value which will is represented by 1/4). I would like to have a value for the numerator (1) and the denominator (4). I am making use of Python's fractions module.

NUMBER = 5.25

from fractions import Fraction
import math

def express_partFraction(NUMBER):
    part = math.modf(NUMBER)[0] 
    return ((Fraction(part)))

express_partFraction(NUMBER)

Currently, I have the following returned which is not indexable:

Fraction(1, 4)

However, I am looking for something like the following:

numerator = express_partFraction(NUMBER)[0]
denominator = express_partFraction(NUMBER)[1]

Which generates this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-486-39196ec5b50b> in <module>()
     10 express_partFraction(NUMBER)
     11 
---> 12 numerator = express_partFraction(NUMBER)[0]
     13 denominator = express_partFraction(NUMBER)[1]

TypeError: 'Fraction' object does not support indexing

Upvotes: 0

Views: 862

Answers (2)

user2357112
user2357112

Reputation: 281683

Fraction objects have numerator and denominator attributes:

numerator = some_fraction.numerator
denominator = some_fraction.denominator

The fact that you're inputting a float will cause you problems, though:

>>> fractions.Fraction(0.1)
Fraction(3602879701896397, 36028797018963968)

There's limit_denominator, which you can use to take a guess at what the fraction "should" be by assuming the denominator isn't too big, but you should really try to avoid a floating-point step entirely. For example, take input as a string:

>>> fractions.Fraction('1.1')
Fraction(11, 10)
>>> fractions.Fraction('1.1') % 1
Fraction(1, 10)
>>> _.numerator
1

Upvotes: 1

Blender
Blender

Reputation: 298432

The Python 2.7 documentation omits the fact that Fraction objects have numerator and denominator attributes. You can find them in the Python 3 documentation.

If you want to see what attributes an unknown object has, just use the dir() function:

>>> x = Fraction(1, 2)
>>> x.numerator
1
>>> x.denominator
2
>>> [a for a in dir(x) if not a.startswith('_')]
['conjugate', 'denominator', 'from_decimal', 'from_float', 'imag', 'limit_denominator', 'numerator', 'real']

Upvotes: 1

Related Questions