如何简化我班级的分数?

时间:2017-05-16 15:36:08

标签: python

这是我的课程Fraction的代码:

class Fraction:
    """Class for performing fraction arithmetic.
    Each Fraction has two attributes: a numerator, n and a deconominator, d.
    Both must be integer and the deonominator cannot be zero.
    """
    def __init__(self,n,d):
        """Performs error checking and standardises to ensure denominator is positive"""
        if type(n)!=int or type(d)!=int:
            raise TypeError("n and d must be integers")
        if d==0:
            raise ValueError("d must be positive")
        elif d<0:
            self.n = -n
            self.d = -d
        else:
            self.n = n
            self.d = d

    def __str__(self):
        """Gives string representation of Fraction (so we can use print)"""
        return(str(self.n) + "/" + str(self.d))

    def __add__(self, otherFrac):
        """Produces new Fraction for the sum of two Fractions"""
        newN = self.n*otherFrac.d + self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __sub__(self, otherFrac):
        """Produces new Fraction for the difference between two Fractions"""
        newN = self.n*otherFrac.d - self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __mul__(self, otherFrac):
        """Produces new Fraction for the product of two Fractions"""
        newN = self.n*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __truediv__(self, otherFrac):
        """Produces new Fraction for the quotient of two Fractions"""
        newN = self.n*otherFrac.d
        newD = self.d*otherFrac.n
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __eq__(self,otherFrac):
        return(self.n * otherFrac.d) == (self.d * otherFrac.n)

为了使课程更有用,我该如何简化课程?

例如:我想将30/15更改为5/3?看起来像:
(30/2)/(18/2)---&gt; 15/9 -----&gt; (15/3)/(9/3)-----&gt; 5/3

我不使用import fraction

1 个答案:

答案 0 :(得分:2)

你想要找到分子和分母的最大公约数并将它们除以。 gcd function位于Python的标准库中,但您可能希望自己实现它。一种着名的(易于实现)算法可以找到它Euclid's algorithm

您可以通过减去两个数字来获得第三个数字(差值)来实现Euclid算法,然后丢弃三个中的最大数字并重复此减法/丢弃过程,直到您的一个数字为零。

顺便说一句,30/15减少了2/1。

举个例子(30/15)

30 - 15 = 15

现在你有3个数字(30,15,15)。丢弃最大的并重复。

15 - 15 = 0

现在你有3个较小的数字(15,15,0)。

15 - 0 = 15

因为这并没有改变这组数字,你可以得出结论,15是你最大的公约数。 (如果你将30和15除以15,你会得到2和1,这是你的分数和分子的分数。