Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The fractions in Homework03 are correct, but not simplified, e.g. 2/4 can be sim

ID: 3755158 • Letter: T

Question

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 elementary school that you can simplify fractions by finding the Greatest Common Factor (GCF) and then dividing the number and denominator. Here's pseudocode for one solution:

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

# the absolute value is important for negative values

for each integer gcf from start down to 2

if numerator mod gcf == 0 and denominator mod gcf == 0 then

gcf is the greatest common factor that evenly divides both the

numerator and denominator

return a new Fraction with numerator / gcf and denominator / gcf

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

Extend your Fractions class from HW03 and add a new simplify(self) method that returns a new Fraction that is simplified or just returns a copy of self if self can't be simplified. 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 a negative numerator or denominator?

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

And the HW03 code is :

Explanation / Answer

import unittest class 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 self.simplify() 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 __ge__(self, other): return (self.num * other.denom) >= (self.denom * other.num) def simplify(self): i = int(max(abs(self.num), self.denom)) while i >= 2: if int(abs(self.num)) % i == 0 and int(self.denom) % i == 0 : self.num = int(self.num / i if self.num > 0 else (-self.num)/i ) self.den = int(self.denom / i) return i -= 1 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 None def 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)
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote