Add reduce_frac (Turn Frac into reduce form)

This commit is contained in:
Sirin Puenggun 2022-11-26 14:58:13 +07:00
parent 1e6a977102
commit 22b41cb4b6

View File

@ -1,3 +1,5 @@
from math import gcd
class Fraction: class Fraction:
def __init__(self, numer, denom): def __init__(self, numer, denom):
if numer < 0 and denom < 0: if numer < 0 and denom < 0:
@ -126,6 +128,18 @@ class Fraction:
denom = self.denom**(-other) denom = self.denom**(-other)
return Fraction(denom, numer) return Fraction(denom, numer)
def reduce_frac(self):
"""
Turn Fraction into reduce form.
>>> m1 = Fraction(2, 4)
>>> m1.reduce_frac()
>>> print(m1)
1/2
"""
temp = gcd(self.numer, self.denom)
self.numer = self.numer // temp
self.denom = self.denom // temp
def __str__(self) -> str: def __str__(self) -> str:
""" """
Print Fraction Form. Print Fraction Form.