Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Sample code for ADA topic 1 Date: 2 0 - 1 0 - 2 0 2 2 Following should be inside ratNum.py

"""
Sample code for ADA topic 1
Date: 20-10-2022
Following should be inside "ratNum.py"
"""
# find greatest common divisor
# using the fact that gcd(a,b)= gcd(b,c) where c = a % b
# if b is zero, gcd(a,b)= gcd(a,0)= a
def gcd(a,b):
while b !=0:
r = a % b
a = b
b = r
return a
# find least common multiple using gcd() function
def lcm(a, b):
return a*b // gcd(a,b)
# ratNum representing rational numbers (a/b)
class ratNum:
# constructor for creating a rational number, default is zero
def __init__(self, a=0, b=1):
self.a = a
if b >0: self.b = b
else:
print("b shound be greater than zero!")
self.b =1
def input(self): # input a rational number from keyboard
while True:
a, b = input("input a/b (b>0): ").split("/")
a, b = int(a), int(b)
if b >0: break
print("b shound be greater than zero!")
self.a = a
self.b = b
def __str__(self): # convert to str for display
return f"{self.a}/{self.b}"
def __add__(self, y): # rational number addition
b = lcm(self.b, y.b)
a = self.a * b // self.b + y.a * b // y.b
return ratNum(a,b)
def __sub__(self, y): # rational number subtraction
b = lcm(self.b, y.b)
a = self.a * b // self.b - y.a * b // y.b
return ratNum(a,b)
def __mul__(self, y): # rational number multiplication
a = self.a * y.a
b = self.b * y.b
g = gcd(a, b);
a = a // g
b = b // g
return ratNum(a,b)
def __truediv__(self, y): # rational number division
if (y.a ==0): print("Division by zero!")
else:
a = self.a * y.b
b = self.b * y.a
g = gcd(a, b)
a = a // g
b = b // g
return ratNum(a,b)
def __eq__(self, y): # comparing two rational numbers
diff =(self - y).a
if diff >0: return 1
elif diff 0: return -1
return 0
# end of "ratNum.py"
# Following should be inside "main.py"
# from ratNum import *
z1= ratNum(); z1.input()
z2= ratNum(); z2.input()
print(z1,"+", z2,"=", z1+z2) # Task 0
print(z1,"-", z2,"=", z1-z2) # Task 1
print(z1,"x", z2,"=", z1*z2) # Task 2
print(z1,"/", z2,"=", z1/z2) # Task 3
print(z1,"==", z2,"=", z1==z2) # Task 4
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

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

Step: 3

blur-text-image

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

Linked Data A Geographic Perspective

Authors: Glen Hart, Catherine Dolbear

1st Edition

1000218910, 9781000218916

More Books

Students also viewed these Databases questions

Question

Differentiate among the types of clinical interviews.

Answered: 1 week ago

Question

What is the cause of this situation?

Answered: 1 week ago

Question

What is the significance or importance of the situation?

Answered: 1 week ago