You are on page 1of 8

UNIVERSITYOFTORONTO MISSISSAUGA

Aids:
APRIL "2012 FINALEXAMINATION
CSC 148H5S
Introduction toComputer Science
Arnold Rosenbloom
Duration- 3hours
Two pages of double sided Letter (8 x 11) sheet;
Student Number:
Last Name:
First Name:
Signature:
(In the meantime, please fill outthe identificationsection above,
Thisfinal examinationconsistsofathreepageappendixANDthisexam
book, with 6 questions on 12 pages (including this one), printed on both
sides of the paper. When you receive the signal to start, please make
sure thatyourcopy of the examination is complete. Answer eachquestion
directlyon theexamination paper,in thespaceprovided.
Beaware that concise, well thought-out answers will be rewarded over
legibly.
The University ofToronto Mississauga and you, as a student, share a
commitment to academic integrity. You are reminded that you may be
charged with an academic offence for possessing any unauthorized aids
during thewriting ofan exam, includingbutnot limited to any electronic
deviceswithstorage,suchascellphones, pagers,personaldigitalassistants
(PDAs), iPods, andMP3 players. Unauthorized calculatorsand notesare
alsonotpermitted. Donothaveanyoftheseitemsinyourpossessioninthe
aids with yourbelongingsatthefront oftheroom before theexamination
begins. If any oftheseitems are keptwith you during thewriting ofyour
exam, you may be charged with an academic offence. A typical penalty
may causeyou tofail thecourse.
exam has begun. exam has begun.
Good Luck!
# 1: /10
# 2: /15
#3: 5
#4: / 5
#5: / 5
# 6: /11
TOTAL;
TotalPages = 12 Page1 OVER..
esc148H5S
FinalExamination APRIL2012
Question 1. [10 MARKS]
Writethefollowing functions recursively
Part (a) [5 MARKS]
To determine ifa number is divisible by three, do the following: Add up all the digits in the number. Find out
whatthesum is. Thesum is divisible by 3ifandonly iftheoriginal number is divisible by 3. For example: 12123
(1+2+1+2+3=9)9is divisible by 3, therefore12123 is too!
Writea recursive routines sum_digits and is_divisible_by_3below. No for loops and while loops allowed.
def sum_digits(n):
'" return the sum of the digits in non-negative integer n
sum_digits(O) returns 0
sum_digits(5) returns 5
sum_digits(17) returns 8
sum_digits(5762) returns 20 '"
# Hint: n%10 is the last digit of n, so 5%10==5, 17%10==7, 5762%10==2
def is_divisible_by_3(n):
'" return True, if non-negative integer n is divisible by 3, and False otherwise '"
# You must use the divisibility by 3 trick and only assume 0, 3, 6 and 9 are divisible by 3.
Student #: '-'-'--'--"'--'---'--'---'---'-...... Page2of12
CONT'D...
APRIL2012 FinalExamination esc148H5S
Part (b) [5 MARKS]
We wish to countthe maximum number ofregions the real planecan be divided into using n lines. 0 lines cutthe
planein 1region. 1line cutstheplanein 2. 2lines can cuttheplanein 4. 3lines can cuttheplanein 7. 4lines can
cut the plane in 11 regions. Writea python function which determines the maximum number ofregions theplane
can be cutinto usingn lines. Explainyourrecursivesolutionintermsoflinesinthe planeandregions.
2 4 7 11
~ A--A
n=l n=2 n=3 n=4
def num_regions(n):
111 return the maximum number of regions the- real plane can be cut into by n lines
I 1 I
num_regions(1)==2, num_regions(2)==4, num_regions(3)==7, num_regions(4)==11...
TotalPages :;: 12 Page3 OVER...
esc148H5 S Final Examination APRIL 2012
Question 2. [15 MARKS]
Draw an appropriate UML Class diagram and write Object Oriented Python code to model the Bank Accounts
scenariodescribed below.
There are two types of bank accounts, Checking and Savings. Each of them has an amount and an account
number. You can deposit and withdraw positive amounts from an account. If a user tries to withdraw more than
thecurrentamount in anaccount, anInsufficientFundsException is raised, and the amount is notwithdrawn. If the
user tries todeposit orwithdraw a negative amount, anInvalidAmountException is raised.
Savings accounts haveaninterest rateassociatedwiththem. Occassionally, interest is paidonanaccount. That
is, theamountis increased by theinterestratetimes theamount in the aocount.
Checkingaccounts do not earninterest, butthey do keep trackofallcheques writtenon them (see theexample
below). Again,ifa userattemptswritingacheckandthereareinsufficientfunds, thenanInsufficientFundsException
is raisedandthecheck is rejected, otherwisethecheck is accepted, recorded andtheamountofthecheckwithdrawn
from theaccount.
if __name__=="__main__":
s=Savings(2345, 2) # create savings account number 2345 with 21. interest rate
print str(s)
s.deposit (100)
s.deposit(150)
print "\tBefore interest\n" + str(s)
s.pay_interest()
print "\tAfter interest\n" + str(s)
s.withdraw(100)
print str(s)
c=Checking(7734) # create checking account number 7734
c.deposit(300)
c.check("Sid". 120)
c.check("Sally", 3)
print str(c)
try:
c.check(IfArnold", 5)
c.check(IIJim", 2.75)
c.check(IJim", 1000) # will cause an exception
c.check("Helen". 25)
except InsufficientFundsException, e:
print e
print str(c)
# ------------------ OUTPUT -----------------------
Savings #2345 \$0 (21.)
Before interest
Savings #2345 \$250 (21.)
After interest
Savings #2345 \$255.0 (21.)
Savings #2345 \$155.0 (21.)
Checking #7734 \$177
(1) To: Sid \$120
(2) To: Sally \$3
Attempt to withdraw 1000 from #7734
Checking #7734 \$169.25
(1) To: Sid \$120
(2) To: Sally \$3
(3) To: Arnold \$5
(4) To: Jim \$2.75
Student #; '--' - - - - - ~ ~ - - - - - - - - - Page4of12 CONT'n
ese 148H5 S Final Examination APRIL 2012
Question 3. [5 MARKS]
example:
if __name__ == ' __main__':
for v in [65. 2. 99. 22. 132. 5. 6]:
print str(l)
# The above code OUTPUTS
# [2.5,6.22.65.99.132.]
Student#: - - ~ - - - - - - - - - - - - - - - - Page 8of12
CONT'O.,
APRIL 2012 Final Examination esc 148H5 S
Question 4. [5 MARKS]
Modify the BSTree in the appendix to this exam so that it supports a longest_path method. This returns a list of
keys on a longest root to leaf path. If there is more than one such path, you are free to return the keys on anyone
of them. For example:
t=BSTreeO
for v in [65, 2, 99, 22, 132, 5, 6]:
t.insert(v)
print t.longest_path()
# OUTPUT: [6, 5, 22, 2, 65]
t=BSTreeO
for v in [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]:
t.insert(v)
print t.longest_path()
# OUTPUT: [15, 14, 12, 8]
OVER..
Total Pages = 12
Page 9
esc148H5S FinalExamination APRIL 2012
Question 5. [5 MARKS}
Writecodetoprinta leveLordertraversalofa BSTree. To do this, specializeBreadthFirstSearchtotheBSTree
codeprovided attheend oftheexam. The level order traversalshould printa node'skey first, thenit'schildren in
left toright order, thenthechildrenschildren in left torightorder, andso on. For example, ifthetreelooked like
6 N=BSTreeNull
/ \
3 8
/ \ / \
N 5 7 9
/\/\ /\
NNNNN N
Thena level order traversal would print: 6 3 8 5 7 9. Hint: use a queue and putBSTreeNode intoit. Printthe
keys asyou dequeue. Remember thata Queue has methodsenqueue, dequeue and is_empty. You can assumethe
theQueue class has been imported.
class BSTree:
def level_order(self):
'" All code for this operation should appear here. There is no
need to add code to BSTreeNode or BSTreeNull III
Page10 of12
CONT'D.
APRIL 2012 Final Examination esc148H5S
Question6. [11 MARKS]
Part (a) [5 MARKS]
As in theassignment, letTl(n) betheidealworst caserunningtimefor /1oninputn (etc.). Inthespaceprovided,
write a bestO(?) runningtimefor each ofpythonfunctions below. You do not need toshow yourwork.
def f1(n): # T_1(n) is in OL__________) Part (b) [1 MARK]
i=j=O
Whatdoes f2Cn) compute?
vhile i<10000;
j=j+1
i=i+1
return j
def f2(n): # T_2(n) is in 0( ___________)
i=j=O
while i<n:
j=j+2*i+1
i-i+1
return j
Part (C) [2 MARKS]
def fS(n): # T_3(n) is in 0(___________) Inthespacebelow, writetheloopinvariantfor f2. Your statement
should betrueeach timetheloopguard (i <n) is checked.
if n<O: return
i=j=O
while j<n:
print i, j
i=i+1
if i==n:
j=j+1
i=O
def f4(n): # T_4(n) is in 0(___________)
saO
for i in range(n): Part (d) [1 MARK]
if i%2==0: # i%2==O only when i is even
What does f3(n) do oninput n?
for j in range(n):
8=s+i
return s
def f5(n): # T_5(n) is in 0( ___________)
s=O
for i in range(n):
if i-n/2==0: # i-n/2==0 only when i==n/2
for j in range(n):
6=6+i
return 8
Part (e) [2 MARKS]
Inthespacebelow, writetheloop invariantfor f3. Yourstatement
should betrueeach timetheloop guard (j<n) is checked.
Page11
OVER...
TotalPages == 12