© All Rights Reserved

7 views

© All Rights Reserved

- Android Project Report
- OS Chapter1
- Personal Digital Assistant
- btree-practice_problem
- SAP BI BW Extraction-libre
- WS RDD WR 204
- OS
- atopk-dasfaa
- Android Based Smart Remote Control
- BGV08
- Data Structures Programs
- Handout
- M-LEARNING - A NEW FORM OF LEARNING AND EDUCATION
- coc
- Information
- Alcatel OT993 - Samsung Galaxy S Duos
- mlerning.docx
- B+ tree & B tree
- DS&OOPS
- D3.8 - Training Material

You are on page 1of 8

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:

Do not turn this page until you have received the signal tostart.

(In the meantime, please fill outthe identificationsection above,

andreadtheinstructions below carefully.)

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

longramblingones. Also, unreadableanswerswillbegivenzero (0) sowrite

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

areaofyour desk. Pleaseturn the electronicsoffandput all unauthorized

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.

Pleasenote, you CANNOTpetitionto re-writeanexaminationoncethe

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.

Asampleexecutionofyour code follows:

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]

ModifytheLinkedListcodeintheappendixtothisexamsothatitsupportsanadd_inordermethod. Thismethod

addsdatatothe linked listso thataforward traversalofthelinked listvisits the datainnon-decreasingorder. For

example:

if __name__ == ' __main__':

l=LinkedList0

for v in [65. 2. 99. 22. 132. 5. 6]:

l.add_lnorder{v)

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

- Android Project ReportUploaded bySahil Adlakha
- OS Chapter1Uploaded byapi-26996193
- Personal Digital AssistantUploaded byUsman
- btree-practice_problemUploaded byRashmi Ranjan
- SAP BI BW Extraction-libreUploaded byfabio
- WS RDD WR 204Uploaded byvenugopal
- OSUploaded bywcqul
- atopk-dasfaaUploaded byomegagm
- Android Based Smart Remote ControlUploaded byasifnpatel
- BGV08Uploaded byAnonymous RrGVQj
- Data Structures ProgramsUploaded byPrabhu
- HandoutUploaded byAnahit Serobyan
- M-LEARNING - A NEW FORM OF LEARNING AND EDUCATIONUploaded bylazarstosic
- cocUploaded byAravind Kumar
- InformationUploaded byhanda789
- Alcatel OT993 - Samsung Galaxy S DuosUploaded byrnx17
- mlerning.docxUploaded byOgakhan Nyamu
- B+ tree & B treeUploaded byRamkaran Jandu
- DS&OOPSUploaded byChristoDeepthi
- D3.8 - Training MaterialUploaded byGianluca Gwynbleidd Quinto
- Tutorial 3Uploaded bywertkh32
- Make Invertinverted list edUploaded byUpasana Bhardwaj
- B TreesUploaded bythskumar
- icvs2006Uploaded byEH
- Prog Assign 1Uploaded byAsad Karim
- Quantum Algorithms to Find Equilibrium in Sequential GamesUploaded byGRD Journals
- Lec4_Part2Uploaded bysamsim1232
- Work Queues GuideUploaded byPraveen Reddy
- Queue.txtUploaded byadil khan
- SV Interprocess synchronization and Communication.pdfUploaded byk k

- ECON 101 Final Practice1Uploaded byexamkiller
- Mgeb02 FinalUploaded byexamkiller
- Eco100y1 Wolfson Tt4 2013wUploaded byexamkiller
- Eco100y1 Wolfson Tt3 2013wUploaded byexamkiller
- Eco100y1 Wolfson Tt2 2012fUploaded byexamkiller
- Eco100 Furlong Tt2 2014sUploaded byexamkiller
- Eco100 Furlong Tt3 2014sUploaded byexamkiller
- MATH115 Exam1 2013W PracticeUploaded byexamkiller
- MATH150_Midterm1_2009SpringUploaded byexamkiller
- STAT112 Midterm1 PracticeUploaded byexamkiller
- MATH263_Mid_2009FUploaded byexamkiller
- STAT111 Exam1 PracticeUploaded byexamkiller
- STAT111 Final PracticeUploaded byexamkiller
- STAT111 Exam2 PracticeUploaded byexamkiller
- STAT220 Midterm PracticeUploaded byexamkiller
- SSC302 Midterm 2010FUploaded byexamkiller
- STAT110 Exam1 2009F Version BUploaded byexamkiller
- STAT110 Exam1 Hendrix PracticeUploaded byexamkiller
- STAT110 Exam3 2009F Version AUploaded byexamkiller
- STAT110 Final 2009Spring PracticeUploaded byexamkiller
- STAT110 Exam3 2009F PracticeUploaded byexamkiller
- STAT110 Exam2 2013Spring Edwards PracticeUploaded byexamkiller
- STAT110 Exam2 2009F PracticeUploaded byexamkiller
- STAT110_Exam2_2009FUploaded byexamkiller
- STAT1100 Final LaurelChiappetta PracticeUploaded byexamkiller
- STAT1100 Exam3 LaurelChiappetta PracticeUploaded byexamkiller
- STAT1100 Exam1 LaurelChiappetta PracitceUploaded byexamkiller
- STAT1100 Exam2 LaurelChiappetta PracitceUploaded byexamkiller
- STAT0200 Final 2009Spring Pfenning PracticeUploaded byexamkiller
- STAT102_Midterm1_2013FUploaded byexamkiller

- Build a Super Simple TaskerUploaded byKanashimi Kotoba
- EIE 07-08 AR Revised SyllabusUploaded byAlapati Nageswara Rao
- ISC Computer Science 2013 Solved PaperUploaded byPrem Shaw
- Data Structures ITUploaded byromeofatima
- 504Uploaded byAnil Tripathi
- Vimba NET ManualUploaded bySinuhe Pahe
- II b.tech Cse r10 Jntuk SyllabusUploaded byVanathi Andiran
- Assignment3_S1_2015Uploaded byAndrew Creevey
- Assignment 2 Algorithms and Data Types.docxUploaded byArash Singh
- Uvm ConfigureUploaded byRajesh Nandi
- DataStructure - Circular, Double Ended, Priority QueuesUploaded byaliyaraza1
- Filter Driver Developer GuideUploaded bydhanpa
- BookMap NT User GuideUploaded byRoseane Sobral
- Lect 6Uploaded byBhaswanth Gandham
- imsdcUploaded bynkjain87
- Data Structures and AlgorithmsUploaded byDeepak Kumar Rajak
- SSISUploaded byjoa
- App-Based Water Tanker Booking, Monitoring & Controlling SystemUploaded byIJSTE
- DSUploaded byadddata
- javaBB2Uploaded byWashington Chen
- Datastructure Practical FileUploaded byNeeraj Soni
- Rexx TrainingUploaded byDeepak Dada
- Finger TreeUploaded byHow Si Yu
- The Collection Framework by Kamalakar DanduUploaded byKamalakar Dandu
- Containers - ClassificationsUploaded bySivaraman P. S.
- NetScaler 10.5 Priority QueuingUploaded bysudharaghavan
- 01 Priority QueuesUploaded byIbad Mohammed
- Cs-72 Solved Assignment 2012 (1)Uploaded byPrince Perky
- MTA Software Development Fundamentals - Books resolved tasksUploaded byVasyl Boliuk
- Troubleshoot and Track BDoc Messages.pdfUploaded byatul

## Much more than documents.

Discover everything Scribd has to offer, including books and audiobooks from major publishers.

Cancel anytime.