Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

The fractions in Homework03 are correct, but not simplified,e.g. 2/4 can be simplified to 1/2, 14/21 can be simplified to 2/3,and 63/9 can be simplified

The fractions in Homework03 are correct, but not simplified,e.g. 2/4 can be simplified to 1/2, 14/21 can be simplified to 2/3,and 63/9 can be simplified to 7/1. Recall from elementaryschool that you can simplify fractions by finding the GreatestCommon Factor (GCF) and then dividing the number and denominator. Here's pseudocode for one solution:

start = the min of abs(numerator) andabs(denominator)

# theabsolute value is important for negative values

for each integer gcf from start down to2

if numerator mod gcf == 0 anddenominator mod gcf == 0 then

gcf isthe greatest common factor that evenly divides both the

numerator and denominator

return a new Fraction with numerator / gcf anddenominator / gcf

if you don't find a gcf, then return a copyof the Fraction because it can't be simplified

Extend your Fractions class from HW03 and add a newsimplify(self) method that returns a new Fraction that issimplified or just returns a copy of self if self can't besimplified. E.g.

str(Fraction(9, 27).simplify()) == str(Fraction(1, 3))

Hint: Note that testing

Fraction(9, 27).simplify() == Fraction(1, 3)

is not sufficient because

Fraction(9, 27) == Fraction(1, 3)

Add unittest cases to test your new method.

Hint: what happens if the fraction has anegative numerator or denominator?

Hint: 8 / 4 == 2.0 so you may want todo int(8/4) before creating a new Fraction.

And the HW03 code is :

import unittestclass Fraction:    """ Support addition, subtraction, multiplication, and division of fractions        with a simple algorithm    """    def __init__(self, num, denom):        """ set num and denom            Raise ValueError on 0 denominator         """        self.num = num        self.denom = denom        if denom == 0:            raise ValueError('0 is an invalid denominator')        if num > 0 and denom < 0:            self.num = -num            self.denom = -denom            def __str__(self):        """ String to display fractions """        return str(self.num) + '/' + str(self.denom)                  def __add__(self, other):        """ Add two fractions using simplest approach and return a new Fraction """        return Fraction(self.num * other.denom + self.denom * other.num, self.denom * other.denom)    def __sub__(self, other):        """ subtract two fractions using simplest approach and return a new Fraction """        return Fraction(self.num * other.denom - self.denom * other.num, self.denom * other.denom)    def __mul__(self, other):        """ Multiply two fractions using simplest approach and return a new Fraction """        return Fraction(self.num * other.num, self.denom * other.denom)    def __truediv__(self, other):        """ Add two fractions using simplest approach.            Division is just invert and multiply            and return a new Fraction        """        return Fraction(self.num * other.denom, self.denom * other.num)    def __eq__(self, other):        """ return True/False if the two fractions are equivalent """        return (self.num * other.denom) == (self.denom * other.num)    def __ne__(self, other):        return (self.num * other.denom) != (self.denom * other.num)    def __lt__(self, other):        return (self.num * other.denom) < (self.denom * other.num)    def __le__(self, other):        return (self.num * other.denom) <= (self.denom * other.num)    def __gt__(self, other):        return (self.num * other.denom) > (self.denom * other.num)    def __ge__(self, other):        return (self.num * other.denom) >= (self.denom * other.num)def get_number(prompt):    """ read and return an integer from the user.    """    while True:        inp = input(prompt)        try:            return float(inp)        except ValueError:            print('Error:', inp, 'is not a number. Please try again...')def get_fraction():    """Ask the user for a numerator and denominator and return a valid Fraction"""    while True:        num = get_number("Enter the numerator:")        denom = get_number("Enter the denominator:")        try:            f = Fraction(num, denom)            return f        except ZeroDivisionError as e:            print(e)def compute(f1, operator, f2):    if operator == '+':        return f1 + f2    elif operator == '-':        return f1 - f2    elif operator == '*':        return f1 * f2    elif operator == '/':        return f1 / f2    else:        print('Error:', operator, 'is an unrecognized operator.')        return Nonedef test_suite():    f12 = Fraction(1, 2)    f34 = Fraction(3, 4)    print('this is the test:', f12, '+', f34, '=', f12 + f34)    print('this is the test:', f12, '-', f34, '=', f12 - f34)    print('this is the test:', f12, '*', f34, '=', f12 * f34)    print('this is the test:', f12, '/', f34, '=', f12 / f34)def main():    """Fraction calculations"""    print('Welcome to the fraction calculator!')    test_suite()    f1 = get_fraction()    operator = input('Operation:(+, -, *, /):')    f2 = get_fraction()    try:        result = compute(f1, operator, f2)        print(result)    except ZeroDivisionError as e:        print(e)class FractionTest(unittest.TestCase):     def test_init(self):        """ verify that the numerator and denominator are set properly """        f = Fraction(3, 4)        self.assertEqual(f.num, 3)        self.assertEqual(f.denom, 4)            def test_str(self):        """ verify that __str__() works properly """        f = Fraction(3, 4)        self.assertEqual(str(f), '3/4')            def test_equal(self):        """test fraction equality """        f1 = Fraction(3, 4)        f2 = Fraction(6, 8)        f3 = Fraction(9, 12)        self.assertTrue(f1 == f1)        self.assertTrue(f1 == f2)        self.assertTrue(f1 == f3)        self.assertTrue(f2 == f3)        self.assertFalse(f1 == Fraction(3, 5))    def test_plus(self):        """ test fraction addition """        f1 = Fraction(3, 4)        f2 = Fraction(1, 2)        f3 = Fraction(1, 3)        f4 = Fraction(-1, 2)        f5 = Fraction(2, -3)        self.assertTrue((f1 + f1) == Fraction(6, 4))        self.assertTrue((f1 + f2) == Fraction(5, 4))        self.assertTrue((f1 + f3) == Fraction(13, 12))        self.assertTrue((f1 + f4) == Fraction(1, 4))        self.assertTrue((f1 + f5) == Fraction(1, 12))        self.assertTrue((f4 + f5) == Fraction(-7, 6))    def test_minus(self):        """test fraction subtract"""        f1 = Fraction(1, 2)        f2 = Fraction(2, 5)        f3 = Fraction(3, 8)        f4 = Fraction(-1, 2)        f5 = Fraction(2, -3)        self.assertTrue((f1 - f3) == Fraction(1, 8))        self.assertTrue((f1 - f2) == Fraction(1, 10))        self.assertTrue((f2 - f3) == Fraction(1, 40))        self.assertTrue((f1 - f4) == Fraction(2, 2))        self.assertTrue((f1 - f5) == Fraction(7, 6))        self.assertTrue((f4 - f5) == Fraction(1, 6))    def test_times(self):        """test fraction multiple"""        f1 = Fraction(2, 3)        f2 = Fraction(3, 5)        f3 = Fraction(4, 7)        f4 = Fraction(-1, 2)        f5 = Fraction(2, -3)        self.assertTrue((f1 * f2) == Fraction(6, 15))        self.assertTrue((f1 * f3) == Fraction(8, 21))        self.assertTrue((f2 * f3) == Fraction(12, 35))        self.assertTrue((f1 * f4) == Fraction(-2, 6))        self.assertTrue((f1 * f5) == Fraction(-4, 9))        self.assertTrue((f4 * f5) == Fraction(2, 6))    def test_divide(self):        """test fraction truedivide"""        f1 = Fraction(1, 2)        f2 = Fraction(3, 5)        f3 = Fraction(4, 7)        f4 = Fraction(-1, 2)        f5 = Fraction(2, -3)        self.assertTrue((f1 / f2) == Fraction(5, 6))        self.assertTrue((f1 / f3) == Fraction(7, 8))        self.assertTrue((f2 / f3) == Fraction(21, 20))        self.assertTrue((f1 / f4) == Fraction(-2, 2))        self.assertTrue((f1 / f5) == Fraction(-3, 4))        self.assertTrue((f4 / f5) == Fraction(3, 4))    def test_notequal(self):        """test fraction notequal"""        f1 = Fraction(1, 2)        f2 = Fraction(3, 5)        f3 = Fraction(4, 7)        self.assertTrue(f1 != f2)        self.assertTrue(f1 != f3)        self.assertTrue(f2 != f3)        self.assertTrue(f1 != Fraction(1, 3))    def test_lessthan(self):        """test fraction less than"""        f1 = Fraction(1, 2)        f2 = Fraction(3, 5)        f3 = Fraction(5, 7)        f4 = Fraction(-1, 2)        f5 = Fraction(2, -3)        self.assertTrue(f1 < f2)        self.assertTrue(f1 < f3)        self.assertTrue(f2 < f3)        self.assertTrue(f4 < f1)        self.assertTrue(f5 < f1)        self.assertTrue(f5 < f4)    def test_lessorequal(self):        """test fraction less than or equal"""        f1 = Fraction(2, 3)        f2 = Fraction(4, 5)        f3 = Fraction(6, 7)        f4 = Fraction(-1, 2)        f5 = Fraction(2, -3)        self.assertTrue(f1 <= f2)        self.assertTrue(f1 <= f3)        self.assertTrue(f2 <= f3)        self.assertTrue(f1 <= f1)        self.assertTrue(f2 <= f2)        self.assertTrue(f3 <= f3)        self.assertTrue(f4 <= f1)        self.assertTrue(f5 <= f1)        self.assertTrue(f4 <= f4)    def test_greaterhan(self):        """test fraction greater than"""        f1 = Fraction(5, 7)        f2 = Fraction(3, 5)        f3 = Fraction(1, 2)        f4 = Fraction(-1, 2)        f5 = Fraction(2, -3)        self.assertTrue(f1 > f2)        self.assertTrue(f1 > f3)        self.assertTrue(f2 > f3)        self.assertTrue(f4 > f5)        self.assertTrue(f1 > f4)        self.assertTrue(f1 > f5)    def test_greaterorequal(self):        """test fraction greater than or equal"""        f1 = Fraction(5, 7)        f2 = Fraction(3, 5)        f3 = Fraction(1, 3)        f4 = Fraction(-1, 2)        f5 = Fraction(2, -3)        self.assertTrue(f1 >= f2)        self.assertTrue(f1 >= f3)        self.assertTrue(f2 >= f3)        self.assertTrue(f1 >= f1)        self.assertTrue(f2 >= f2)        self.assertTrue(f3 >= f3)        self.assertTrue(f1 >= f4)        self.assertTrue(f1 >= f5)        self.assertTrue(f4 >= f5)if __name__ == '__main__':    # note: there is no main(). Only test cases here    main()    unittest.main(exit = False, verbosity = 2)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

Extending the Fraction Class to Simplify Fractions We will extend the provided Fraction class by adding a simplifyself method which simplifies the fraction using the Greatest Common Factor GCF Here is ... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Computer Performance Engineering 10th European Workshop Epew 2013 Venice Italy September 17 2013 Proceedings

Authors: Maria Simonetta Balsamo ,William Knottenbelt ,Andrea Marin

2013 Edition

3642407242, 978-3642407246

More Books

Students also viewed these Programming questions

Question

12. What is the basis for setting tolerance?

Answered: 1 week ago