In Python 2, fractions divide in integers. Floats are truncated, so 5 / 6 is zero, and 2 / 6 is zero.
We don’t have this issue in Python 3, but in version 2 we just have to make sure that one of the operands is a float. Note the dot, below:
5 / 6.
2 / 6.
Similar to how we do it on paper… Add the numerators when the denominators are the same. 2 / 6 + 5 / 6 = 7 / 6
However it is not that simple unless we can parse out the numerators and denominators. It can be a lot of work.
In maths we learn that any real number with repeating decimal fraction can be shown as a rational number (a fraction, as it were).
1 + 1 / 6
It’s an interesting concept but it takes learning and a good bit of logic so add it to your special projects list for later on down the road. The topic did come up a few years back, maybe in a challenge or in the Town Square.
We have a tool in Python, the fractions module, which gives us the Fraction class. This gives us ways to add, subtract, multiply and divide fractions. Given their nature, the result is always another fraction, right? Makes this module a no-brainer to do the heavy lifting with fractions in Python.
>>> from fractions import Fraction
>>> pi = Fraction(22, 7)
>>> e = Fraction(19, 7)
>>> pi + e
What science will be needed to find that missing 1?