CS Prelim 2 Review Fall 2017

Similar documents
CS Prelim 2 Review Fall 2015

CS Prelim 2 Review Fall 2014

CS Prelim 2 Review Fall 2018

CS Prelim 2 Review Fall 2012

CS Prelim 1 Review Fall 2012

CS1110. Lecture 22: Prelim 2 Review Session. Announcements. Processed prelim regrade requests: on the front table.

CS 1110 Prelim 2 November 13th, 2014

CS 1110 Prelim 2 November 14th, 2013

CS 1110 Prelim 2 November 6th, 2012

PREPARING FOR THE FINAL EXAM

CS Prelim 1 Review Fall 2018

CS 1110 Prelim 2 November 10th, 2016

CS Prelim 1 Review Fall 2017

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Prelim 2 November 12th, 2015

CS 1110 Final, December 8th, Question Points Score Total: 100

PREPARING FOR PRELIM 1

CS Prelim 1 Review Fall 2016

PREPARING FOR PRELIM 2

CS Prelim 1 Review Fall 2013

CS 1110 Final, December 16th, 2013

PREPARING FOR THE FINAL EXAM

Review 3. Exceptions and Try-Except Blocks

CS 1110 Prelim 2 November 12th, 2015

Lecture 11. Asserts and Error Handling

CS Prelim 1 Review Fall 2013

CS1110. Lecture 1: Final review session. Review materials See website for a version of last year s final with conventions redone to match this year.

Lecture 20. Subclasses & Inheritance

Lecture 19. Operators and Abstraction

Lecture 18. Classes and Types

CS 1110 Final, December 9th, Question Points Score Total: 100

Lecture 11. Asserts and Error Handling

Review 2. Classes and Subclasses

Lecture 21. Programming with Subclasses

CS Lecture 26: Grab Bag. Announcements

CS 1110 Final, December 16th, 2013

CS 1110 Prelim 2 Solutions April 2018

CS 1110 Final, December 17th, Question Points Score Total: 100

CS Lecture 19: Loop invariants

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014

CS 1110: Introduction to Computing Using Python Loop Invariants

Lecture 19. Using Classes Effectively

CS 1110 Prelim 1 October 4th, 2012

Lecture 21. Programming with Subclasses

CS 1110 Prelim 1 October 17th, 2013

Lecture 21. Programming with Subclasses

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

Structure and Flow. CS 3270 Chapter 5

CS 1110 Final Exam, May 2018

CS 1110 Final, December 7th, 2017

CS 1110 Prelim 1 October 15th, 2015

isinstance and While Loops

Lecture 19: Subclasses & Inheritance (Chapter 18)

Lecture 22. While Loops

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Review 1. Call Frames; Diagramming Objects

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Lecture 17: Classes (Chapter 15)

Lecture 9. Memory and Call Stacks

CSC148 Recipe for Designing Classes

Lecture 7. Memory in Python

CS 1110 Final Exam Solutions May 2018

Abstract Data Types Chapter 1

Iteration and For Loops

Lecture 17: Classes (Chapter 15)

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

CS 1110 Final, May 2017

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

Data Structures (list, dictionary, tuples, sets, strings)

CS 1110 Final Exam May 9th, 2013 SOLUTIONS

Announcements for This Lecture

Exam #3, Form 3 A CSE 231 Fall 2015 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Lecture 15. More Recursion

Review 4. Lists and Sequences

Overview of List Syntax

Lecture 11: Iteration and For-Loops

Prelim 1. CS 2110, 13 March 2018, 7:30 PM Total Question Name Short answer

CSE 160 Winter 2016: Final Exam

RECURSION (CONTINUED)

CS 1110, Spring 2018: Prelim 1 study guide Prepared Tuesday March 6, 2018

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

RECURSION (CONTINUED)

XC Total Max Score Grader

Structure and Interpretation of Computer Programs

CS1110 Lab 6 (Mar 17-18, 2015)

CS100J Prelim I, 29 Sept. 2003

Name: utorid: U of T

Python Mini Lessons last update: May 29, 2018

Lecture 18. Using Classes Effectively

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

Lecture 24: Loop Invariants

Sorting and Searching

Practical Questions CSCA48 Week 6

Structure and Interpretation of Computer Programs

Object-Oriented Design Lecture 16 CS 3500 Fall 2010 (Pucella) Friday, Nov 12, 2010

Structure and Interpretation of Computer Programs

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Transcription:

CS 1110 Prelim 2 Review Fall 2017

Exam Info Prelim 2: 7:30 9:00PM, Thursday, Nov. 9th Last name A J in Uris G01 Last name K Z in Statler Auditorium SDS Students will get an e-mail To help you study: Study guides, review slides are online Review solution to prelim 1 (esp. call stack!) Review solution to Assignment 5 (posted soon) 11/5/17 Prelim 2 Review 2

What is on the Exam? Five questions from the following topics: Recursion (Lab 8, A4) Iteration and Lists (Lab 7, A4, A6) Defining classes (Lab 9, Lab 10, A6) Drawing folders (Lecture, A5) Exceptions (Lectures 11 and 21) Short Answer (Terminology, Potpourri) +2 points for name, netid AND SECTION 11/5/17 Prelim 2 Review 3

What is on the Exam? Recursion (Lab 8, A4) Will be given a function specification Implement it using recursion May have an associated call stack question Iteration and Lists (Lab 7, A4, A6) Defining classes (Lab 9, Lab 10, A6) Drawing folders (Lecture, A5) Exceptions (Lectures 11 and 21) Short Answer (Terminology, Potpourri) 11/5/17 Prelim 2 Review 4

Recursive Function (Fall 2014) def histogram(s): """Return: a histogram (dictionary) of the # of letters in string s. The letters in s are keys, and the count of each letter is the value. If the letter is not in s, then there is NO KEY for it in the histogram. Example: histogram('') returns {}, histogram('abracadabra') returns {'a':5,'b':2,'c':1,'d':1,'r':2} Precondition: s is a string (possibly empty) of just letters.""" 11/5/17 Prelim 2 Review 5

Recursive Function (Fall 2014) def histogram(s): """Return: a histogram (dictionary) of the # of letters in string s. The letters in s are keys, and the count of each letter is the value. If the letter is not in s, then there is NO KEY for it in the histogram. Precondition: s is a string (possibly empty) of just letters.""" Hint: Use divide-and-conquer to break up the string Get two dictionaries back when you do Pick one and insert the results of the other 11/5/17 Prelim 2 Review 6

Recursive Function def histogram(s): """Return: a histogram (dictionary) of the # of letters in string s.""" if s == '': # Small data return {} # left = { s[0]: 1 }. No need to compute this right = histogram(s[1:]) if s[0] in right: right[s[0]] = right[s[0]]+1 else: right[s[0]] = 1 return right # Combine the answer 11/5/17 Prelim 2 Review 7

Call Stack Question def skip(s): """Returns: copy of s Odd (from end) skipped""" 1 result = '' 2 if (len(s) % 2 = 1): 3 result = skip(s[1:]) 4 elif len(s) > 0: 5 result = s[0]+skip(s[1:]) 6 return result Call: skip('abc') Recursive call results in four frames (why?) Consider when 4th frame completes line 6 Draw the entire call stack at that time Do not draw more than four frames! 11/5/17 Prelim 2 Review 8

Call Stack Question def skip(s): """Returns: copy of s Odd (from end) skipped""" 1 result = '' 2 if (len(s) % 2 = 1): 3 result = skip(s[1:]) 4 elif len(s) > 0: 5 result = s[0]+skip(s[1:]) 6 return result Call: skip('abc') skip 3 s 'abc' result skip 5 s 'bc' result skip 3 s 'c' result skip s '' '' '' '' result RETURN 11/5/17 Prelim 2 Review 9 '' ''

Call Stack Question def skip(s): """Returns: copy of s Odd (from end) skipped""" s = 'abc' 1 result = '' s = 'c' 2 if (len(s) % 2 = 1): 3 result = skip(s[1:]) 4 elif len(s) > 0: 5 result = s[0]+skip(s[1:]) 6 return result s = '' s = 'bc' Call: skip('abc') skip 3 s 'abc' result skip 5 s 'bc' result skip 3 s 'c' result RETURN 11/5/17 Prelim 2 Review 10 skip result s '' '' '' '' '' '' Done Line 6

What is on the Exam? Recursion (Lab 8, A4) Iteration (Lab 7, A4, A6) Again, given a function specification Implement it using a for-loop May involve 2-dimensional lists Defining classes (Lab 9, Lab 10, A6) Drawing folders (Lecture, A5) Exceptions (Lectures 11 and 21) Short Answer (Terminology, Potpourri) 11/5/17 Prelim 2 Review 11

Implement Using Iteration def evaluate(p, x): """Returns: The evaluated polynomial p(x) We represent polynomials as a list of floats. In other words [1.5, 2.2, 3.1, 0, 1.0] is 1.5 2.2x + 3.1x**2 + 0x**3 x**4 We evaluate by substituting in for the value x. For example evaluate([1.5, 2.2,3.1,0, 1.0], 2) is 1.5 2.2(2)+3.1(4) 1(16) = 6.5 evaluate([2], 4) is 2 Precondition: p is a list (len > 0) of floats, x is a float""" 11/5/17 Prelim 2 Review 12

Implement Using Iteration def evaluate(p, x): """Returns: The evaluated polynomial p(x) Precondition: p is a list (len > 0) of floats, x is a float""" sum = 0 xval = 1 for c in p: sum = sum + c*xval xval = xval * x return sum # coefficient * (x**n) 11/5/17 Prelim 2 Review 13

Example with 2D Lists (Like A6) def max_cols(table): """Returns: Row with max value of each column We assume that table is a 2D list of floats (so it is a list of rows and each row has the same number of columns. This function returns a new list that stores the maximum value of each column. Examples: max_cols([ [1,2,3], [2,0,4], [0,5,2] ]) is [2,5,4] max_cols([ [1,2,3] ]) is [1,2,3] Precondition: table is a NONEMPTY 2D list of floats""" 11/5/17 Prelim 2 Review 14

Example with 2D Lists (Like A6) def max_cols(table): """Returns: Row with max value of each column Precondition: table is a NONEMPTY 2D list of floats""" # Use the fact that table is not empty result = table[0][:] # Make a copy, do not modify table. # Loop through rows, then loop through columns for row in table: for k in range(len(row)) if row[k] > result[k] result[k] = row[k] return result 11/5/17 Prelim 2 Review 15

What is on the Exam? Recursion (Lab 8, A4) Iteration (Lab 7, A4, A6) Defining Classes (Lab 9, Lab 10, A6) Given a specification for a class Also given a specification for a subclass Will fill in blanks for both Drawing folders (Lecture, A5) Exceptions (Lectures 11 and 21) Short Answer (Terminology, Potpourri) 11/5/17 Prelim 2 Review 16

class Customer(object): """Instance is a customer for our company Mutable attributes: _name: last name [string or None if unknown] _email: e-mail address [string or None if unknown] Immutable attributes: _born: birth year [int > 1900; -1 if unknown]""" # DEFINE GETTERS/SETTERS HERE # Enforce all invariants and enforce immutable/mutable restrictions # DEFINE INITIALIZER HERE # Initializer: Make a Customer with last name n, birth year y, e-mail address e. # E-mail is None by default # Precondition: parameters n, y, e satisfy the appropriate invariants # OVERLOAD STR() OPERATOR HERE # Return: String representation of customer # If e-mail is a string, format is 'name (email)' # If e-mail is not a string, just returns name 11/5/17 Prelim 2 Review 17

class Customer(object): """Instance is a customer for our company Mutable attributes: _name: last name [string or None if unknown] _email: e-mail address [string or None if unknown] Immutable attributes: _born: birth year [int > 1900; -1 if unknown]""" # DEFINE GETTERS/SETTERS HERE def getname(self): return self._name Getter def setname(self,value): assert value is None or isinstance(value, str) self._name = value Setter Actual Exam Question probably not this long. Just for this practice. 11/5/17 Prelim 2 Review 18

class Customer(object): """Instance is a customer for our company Mutable attributes: _name: last name [string or None if unknown] _email: e-mail address [string or None if unknown] Immutable attributes: _born: birth year [int > 1900; -1 if unknown]""" # DEFINE GETTERS/SETTERS HERE. def getemail(self): return self._email Getter def setemail(self,value): assert value is None or isinstance(value, str) self._email = value Setter Actual Exam Question probably not this long. Just for this practice. 11/5/17 Prelim 2 Review 19

class Customer(object): """Instance is a customer for our company Mutable attributes: _name: last name [string or None if unknown] _email: e-mail address [string or None if unknown] Immutable attributes: _born: birth year [int > 1900; -1 if unknown]""" # DEFINE GETTERS/SETTERS HERE. def getborn(self): return self._born Getter Actual Exam Question probably not this long. Just for this practice. Immutable. No Setter! 11/5/17 Prelim 2 Review 20

class Customer(object): """Instance is a customer for our company Mutable attributes: _name: last name [string or None if unknown] _email: e-mail address [string or None if unknown] Immutable attributes: _born: birth year [int > 1900; -1 if unknown]""" # DEFINE GETTERS/SETTERS HERE # DEFINE INITIALIZER HERE def init (self, n, y, e=none): assert isinstance(value, int) and (y > 1900 or y == -1) self.setname(n) # Setter handles asserts self.setemail(e) # Setter handles asserts self._born = y # No setter Actual Exam Question probably not this long. Just for this practice. 11/5/17 Prelim 2 Review 21

class Customer(object): """Instance is a customer for our company Mutable attributes: _name: last name [string or None if unknown] _email: e-mail address [string or None if unknown] Immutable attributes: _born: birth year [int > 1900; -1 if unknown]""" # DEFINE GETTERS/SETTERS HERE # DEFINE INITIALIZER HERE # OVERLOAD STR() OPERATOR HERE def str (self): if self._email is None: return = '' if self._name is None else self._name else: s = '' if self._name is None else self._name return s+'('+self._email+')' Actual Exam Question probably not this long. Just for this practice. None or str If not None, always a str 11/5/17 Prelim 2 Review 22

class PrefCustomer(Customer): """An instance is a 'preferred' customer Mutable attributes (in addition to Customer): _level: level of preference [One of 'bronze', 'silver', 'gold'] """ # DEFINE GETTERS/SETTERS HERE # Enforce all invariants and enforce immutable/mutable restrictions # DEFINE INITIALIZER HERE # Initializer: Make a new Customer with last name n, birth year y, # e-mail address e, and level l # E-mail is None by default # Level is 'bronze' by default # Precondition: parameters n, y, e, l satisfy the appropriate invariants # OVERLOAD STR() OPERATOR HERE # Return: String representation of customer # Format is customer string (from parent class) +', level' # Use str from Customer in your definition 11/5/17 Prelim 2 Review 23

class PrefCustomer(Customer): """An instance is a 'preferred' customer Mutable attributes (in addition to Customer): _level: level of preference [One of 'bronze', 'silver', 'gold'] """ # DEFINE GETTERS/SETTERS HERE def getlevel(self): return self._level Getter Actual Exam Question will not be this long. Just for this practice. def setlevel(self,value): assert isinstance(value, str) assert (value == 'bronze' or value == 'silver' or value == 'gold') self._level = value Setter 11/5/17 Prelim 2 Review 24

class PrefCustomer(Customer): """An instance is a 'preferred' customer Mutable attributes (in addition to Customer): _level: level of preference [One of 'bronze', 'silver', 'gold'] """ # DEFINE GETTERS/SETTERS HERE # DEFINE INITIALIZER HERE def init (self, n, y, e=none, l='bronze'): super(). init (n,y,e) self.setlevel(l) # Setter handles asserts Actual Exam Question will not be this long. Just for this practice. # OVERLOAD STR() OPERATOR HERE def str (self): return super(). str ()+', '+self._level Using super() in place of self uses parent str 11/5/17 Prelim 2 Review 25

What is on the Exam? Recursion (Lab 7, A4) Iteration and Lists (Lab 6, A4, A5) Defining classes (Lab 8, Lab 9, A5) Drawing class folders (Lecture, A5) Given a skeleton for a class Also given several assignment statements Draw all folders and variables created Exceptions (Lectures 11 and 21) Short Answer (Terminology, Potpourri) 11/5/17 Prelim 2 Review 26

Two Example Classes class CongressMember(object): """Instance is legislator in congress Instance attributes: _name: Member's name [str]""" def getname(self): return self._name def setname(self,value): assert isinstance(value, str) self._name = value def init (self,n): self.setname(n) # Use the setter def str (self): return 'Honorable '+self.name class Senator(CongressMember): """Instance is legislator in congress Instance attributes (plus inherited): _state: Senator's state [str]""" def getstate(self): return self._state def setname(self,value): assert isinstance(value, str) self._name = 'Senator '+value def init (self,n,s): assert isinstance(value, str) and len(s) == 2 super(). init (n) self._state = s def str (self): return (super(). str ()+ ' of '+self.state) 11/5/17 Prelim 2 Review 27

Execute the Following Code >>> b = CongressMember('Jack') >>> c = Senator('John', 'NY') >>> d = c >>> d.setname('clint') Remember: Commands outside of a function definition happen in global space Draw two columns: Global space Heap space Draw both the Variables created Object folders created Class folders created If an attribute changes Mark out the old value Write in the new value 11/5/17 Prelim 2 Review 28

Global Space Heap Space b id1 id1 CongressMember _name 'Jack' c id2 id2 Senator d id2 _name 'Senator John' 'Senator Clint' _state 'NY' CongressMember init (self,n) getname(self) str (self) setname(self,value) Senator(CongressMember) init (self,n,s) getstate(self) str (slf) setname(self,value) 11/5/17 Prelim 2 Review 29

Global Space Heap Space b Instance attributes id1 in object folders id1 CongressMember _name 'Jack' c d id2 Methods and class attributes in class id2 folders id2 Senator _name 'Senator John' _state 'NY' 'Senator Clint' Superclass CongressMember init (self,n) getname(self) str (self) setname(self,value) Senator(CongressMember) init (self,n,s) getstate(self) str (slf) setname(self,value) 11/5/17 Prelim 2 Review 30

Global Space Heap Space b id1 id1 CongressMember _name 'Jack' c id2 d id2 Method parameters. id2 Senator _name 'Senator John' _state 'NY' 'Senator Clint' CongressMember init (self,n) getname(self) str (self) setname(self,value) Senator(CongressMember) init (self,n,s) getstate(self) str (slf) setname(self,value) 11/5/17 Prelim 2 Review 31

Method Overriding Heap Space class Senator(CongressMember): """Instance is legislator in congress Instance attributes (plus inherited): _state: Senator's state [str]""" def getstate(self): return self._state id1 CongressMember _name 'Jack' id2 Senator def setname(self,value): assert isinstance(value, str) self._name = 'Senator '+value _name 'Senator John' _state 'NY' 'Senator Clint' def init (self,n,s): assert type(s) == str and len(s) == 2 super(). init (n) self._state = s init calls setter as a helper def str (self): return (super(). str ()+ ' of '+self.state) 11/5/17 Prelim 2 Review 32

What is on the Exam? Recursion (Lab 8, A4) Iteration and Lists (Lab 7, A4, A6) Defining classes (Lab 9, Lab 10, A6) Drawing class folders (Lecture, A5) Exceptions (Lectures 11 and 21) Try-except tracing (skipped on Prelim 1) But now with dispatch on type Will give you exception hierarchy Short Answer (Terminology, Potpourri) 11/5/17 Prelim 2 Review 33

Exceptions and Dispatch-On-Type def first(x): print 'Starting first.' try: second(x) except IOError: print 'Caught at first print 'Ending first def third(x): print 'Starting third.' if x < 0: raise IOError() elif x > 0: raise AssertionError() print Ending third.' def second(x): print 'Starting second.' try: third(x) except AssertionError: print 'Caught at second print 'Ending second What is the output of first(-1)? HINT: StandardError AssertionError IOError 11/5/17 Prelim 2 Review 34

Exceptions and Dispatch-On-Type def first(x): print 'Starting first.' try: second(x) except IOError: print 'Caught at first print 'Ending first def third(x): print 'Starting third.' if x < 0: raise IOError() elif x > 0: raise AssertionError() print Ending third.' def second(x): print 'Starting second.' try: third(x) except AssertionError: print 'Caught at second print 'Ending second What is the output of first(-1)? Starting first. Starting second. Starting third. Caught at first. Ending first. 11/5/17 Prelim 2 Review 35

Exceptions and Dispatch-On-Type def first(x): print 'Starting first.' try: second(x) except IOError: print 'Caught at first print 'Ending first def third(x): print 'Starting third.' if x < 0: raise IOError() elif x > 0: raise AssertionError() print Ending third.' def second(x): print 'Starting second.' try: third(x) except AssertionError: print 'Caught at second print 'Ending second What is the output of first(1)? 11/5/17 Prelim 2 Review 36

Exceptions and Dispatch-On-Type def first(x): print 'Starting first.' try: second(x) except IOError: print 'Caught at first print 'Ending first def third(x): print 'Starting third.' if x < 0: raise IOError() elif x > 0: raise AssertionError() print Ending third.' def second(x): print 'Starting second.' try: third(x) except AssertionError: print 'Caught at second print 'Ending second What is the output of first(1)? Starting first. Starting second. Starting third. Caught at second. Ending second. Ending first. 11/5/17 Prelim 2 Review 37

What is on the Exam? Recursion (Lab 7, A4) Iteration and Lists (Lab 6, A4, A5) Defining classes (Lab 8, Lab 9, A5) Drawing class folders (Lecture, Study Guide) Exceptions (Lectures 11 and 21) Short Answer (Terminology, Potpourri) See the study guide Look at the lecture slides Read relevant book chapters In that order 11/5/17 Prelim 2 Review 38

Any More Questions? 11/5/17 Prelim 2 Review 39