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

This programming lab will look at using a class you design yourself. Implement a

ID: 3695161 • Letter: T

Question

This programming lab will look at using a class you design yourself.

Implement a class to represent a Fraction. The class should have the following attributes and methods:

Instance variables for numerator and denominator

A constructor: init (self, n, d)

n is an integer indicating the numerator of the fraction and d is an integer indicating the de- nominator of the fraction. This constructor should create a fraction with the given numerator and denominator.

Accessor/get methods for both instance variables

Mutator/set methods for both instance variables

str (self)
Returns a string representation of the fraction.

A method addFraction that has the following specification:

Two fractions can be added using the formula:
a + c = ad + bc.

b d bd

After writing your class, write a main function to create and use some Fraction objects. Here is some sample output for using the Fraction objects:

Explanation / Answer

class Fraction:
def __init__(self, n,d):
self.n = n
self.d = d
def getnum(self):
return self.n
def getden(self):
return self.d
def setnum(self,n):
self.n=n
def setden(self,d):
self.d=d
def str(self):
return str(self.n)+'/'+str(self.d)
def addFraction(self,n,d):
nm = self.n*d+self.d*n
dm = self.d*d
print("The sum is:",str(nm)+'/'+str(dm))
def main():
f1 = Fraction(1,2)
print("The fraction is:",f1.str())
f2 = Fraction(1,4)
print("The fraction is:",f2.str())
print("Add",f1.str(),"and",f2.str())
f1.addFraction(f2.getnum(),f2.getden())
main()

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