Background: University of The West Indies Department of Computing COMP1127-Introduction To Computing II Tutorial 2A
Background: University of The West Indies Department of Computing COMP1127-Introduction To Computing II Tutorial 2A
Department of Computing
COMP1127Introduction to Computing II
Tutorial 2A
Background
The mathematical rules for performing calculations on rational numbers are as follows:
Tutorial Problem 1
a) Assume that two rational numbers r1 and r2 need to be added, where r1 and r2 are tuples of
numerator and denominator, Define a function naive-add that returns the sum of r1 and r2.
b) The software vendor Rational Numbers Inc. defines a constructor for a rational number using the
function make-rational below.
def make_rational(numer, denom):
return ["rational",numer,denom)]
Complete Rationals rational number ADT by implementing functions get_numer and get_denum
that return the numerator and denominator respectively, given a rational number r.
c) Use the rational number ADT to implement the functions rat_add, rat_subt, rat_mult and
rat_div that implement addition, subtraction, multiplication and division of rational numbers
respectively.
d) Quite often it is required that a rational number be written in its simplest terms, by dividing both the
numerator and the denominator by the greatest common divisor. The function gcd, given below,
returns the greatest common divisor of two numbers given as arguments.
def gcd(num1, num2):
if num2 ==0 :
return num1
else:
return gcd (num2, num1%num2)
Redefine the ADT constructor make-rat so that a rational number is expressed in its simplest terms.
Tutorial Problem 2
A disgruntled employee of Rational Numbers Inc decides to resign from the company and then gets a
court injunction granted to prevent Rational from using the ADT implementation of question 1. Rationals
board of directors does not see this as a major problem, bearing in mind the range of choices for creating
compound data structures. They decide to re-define the constructor of their ADT using the data structure
dictionary as follows (before the GCD update):
def make_rational(numer, denom):
return {"numer":numer, "denom" : denom}
a) Create the new versions of the functions get_numer and get_denom, and the updated constructor
that simplifies the rational number.
b) Will any of the functions defined in Problem 1 (c) stop working after the new ADT implementation?