1

I have a code that is supposed to simplify fractions. But i couldn't create simplify-method correctly.

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

It should give

>>> frac = Fraction(-2, -4)
>>> frac.return_string()
'2/4'
>>> frac.simplify()
>>> frac.return_string()
'1/2'

So basically i have problem creating simplify-method. I also know you can import fractions but i'm not going to need that.

J.Doe
  • 27
  • 1
  • 4
  • 1
    You should probably attempt to do your homework first by yourself, and then when you run into problems, come asking about those specific problems. – Christian W. Mar 20 '17 at 11:45
  • 1
    You need to attach something, SO community won't write you `simplify` function from scratch. – vishes_shell Mar 20 '17 at 11:45
  • 1
    just divide with the greatest common divisor... ;) – ewcz Mar 20 '17 at 11:46
  • 1
    Think about how you could use the [greatest common divisor](https://stackoverflow.com/questions/11175131/code-for-greatest-common-divisor-in-python) to help simultaneously divide the numerator and divisor in a loop. – Cory Kramer Mar 20 '17 at 11:49

1 Answers1

4

The fractions module can simplify fractions.

>>> from fractions import Fraction
>>> Fraction(120, 35)
Fraction(24, 7)

if you want to know more, look at Does Python have a function to reduce fractions?.

CoderCookie10
  • 81
  • 1
  • 10