我有一个应该简化分数的代码。但我无法正确创建简化方法。
class Fraction:
""" This class represents one single fraction that consists of
numerator and denominator """
def __init__(self, numerator, denominator):
"""
Constructor. Checks that the numerator and denominator are of
correct type and initializes them.
:param numerator: fraction's numerator
:param denominator: fraction's denominator
"""
if not isinstance(numerator, int) or not isinstance(denominator, int):
raise TypeError
elif denominator == 0:
raise ValueError
self.__numerator = numerator
self.__denominator = denominator
def return_string(self):
""" Returns a string-presentation of the fraction in the format
numerator/denominator """
if self.__numerator * self.__denominator < 0:
sign = "-"
else:
sign = ""
return "{:s}{:d}/{:d}".format(sign, abs(self.__numerator),
abs(self.__denominator))
def simplify(self):
""" simplify fraction """
def greatest_common_divisor(a, b):
"""
Euclidean algorithm.
"""
while b != 0:
a, b = b, a % b
return a
应该给出
>>> frac = Fraction(-2, -4)
>>> frac.return_string()
'2/4'
>>> frac.simplify()
>>> frac.return_string()
'1/2'
所以基本上我有创建简化方法的问题。我也知道你可以输入分数,但我不需要那个。
答案 0 :(得分:3)
分数模块可以简化分数。
>>> from fractions import Fraction
>>> Fraction(120, 35)
Fraction(24, 7)
如果您想了解更多信息,请查看Does Python have a function to reduce fractions?。