Rational Numbers
Write a class Rational to represent a
rational number p/q, where both p and q are integers, and by
definition the
denominator q should not be equal to 0.
Your class should implement the following methods:
- __init__(self, p, q)
Creates a rational number and stores p, q as the numerator and
denominator, respectively.
- reduce(self)
Calculates the greatest common divisor (gcd) of the numerator and the
denominator, and divide them by gcd.
For example, after the reduction, 24/36 becomes 2/3.
- __str__(self)
Return a string representing the rational number with the format
p/q.
If q is equal to 1, you may omit the portion of "/q" and simply return
the portion for "p".
You may test your class with the following main program:
def main():
a = Rational(24, 36)
print(a)
a.reduce()
print(a)
if __name__ == "__main__":
main()
The result may look like:
24/36
2/3