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

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

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

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

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

CS 1110 Final, December 16th, 2013

CS 1110 Final, December 16th, 2013

CS 1110 Final, December 7th, 2017

CS 1110 Prelim 1 October 4th, 2012

CS 1110 Prelim 2 November 13th, 2014

CS 1110 Prelim 1 October 17th, 2013

CS 1110 Prelim 2 November 14th, 2013

CS 1110 Prelim 1 October 15th, 2015

CS 1110 Prelim 2 November 12th, 2015

CS 1110 Prelim 2 November 10th, 2016

CS 1110 Prelim 1 October 12th, 2017

CS 1110 Prelim 2 November 12th, 2015

CS 1110 Prelim 2 November 6th, 2012

CS 1110 Prelim 2 April 22, 2014

Review 4. Lists and Sequences

Overview of List Syntax

CS 1110, LAB 13: SEQUENCE ALGORITHMS

PREPARING FOR PRELIM 2

PREPARING FOR THE FINAL EXAM

CS 1110 Final Exam May 9th, 2013 SOLUTIONS

CS 1110 Final Exam, May 2018

PREPARING FOR PRELIM 1

CS 1110: Introduction to Computing Using Python Loop Invariants

PREPARING FOR THE FINAL EXAM

CS 1110 Final, May 2017

Lecture 25. Sequence Algorithms (Continued)

Lecture 17: Classes (Chapter 15)

CS Prelim 1 Review Fall 2013

CS1110 Lab 5: Practice for A4 (Mar 8-9, 2016) First Name: Last Name: NetID:

CS 1110 Prelim 1 March 15th, 2016

CS 1110 Final Exam Solutions May 15th, 2014

CS Prelim 2 Review Fall 2014

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Sorting and Searching

CS Prelim 2 Review Fall 2018

CS 1110 Prelim 1, March 2018

CSE wi Midterm Exam 2/8/18. Name UW ID #

Lecture 24. GUI Applications

: Intro Programming for Scientists and Engineers Final Exam

CS 1110 Prelim 2 April 26th, 2016

CS Prelim 2 Review Fall 2015

CS 1110 Prelim 1 March 10, 2015

CS 1110 Regular Prelim 1, March 14th, 2017

CS 1110 Final Exam Solutions May 2018

CS Prelim 2 Review Fall 2017

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

CS Prelim 2 Review Fall 2012

Lecture 17: Classes (Chapter 15)

Abstract Data Types Chapter 1

CS1110 Lab 6 (Mar 17-18, 2015)

CS Prelim 1 Review Fall 2013

Announcements for This Lecture

Lecture 24. GUI Applications

CS 1110 Prelim 1 March 7th, 2013

CS 1110 SPRING 2016: LAB 3: PRACTICE FOR A2 (Feb 23-24)

Announcements for This Lecture

Lecture 4. Defining Functions

CS 1110: WORKED EXAMPLES REGARDING LOOPS AND INVARIANTS

XC Total Max Score Grader

CS Prelim 1 Review Fall 2017

CS 1110 Prelim 2 Solutions April 2018

CS 1110 Prelim 2 April 21, 2015

DSC 201: Data Analysis & Visualization

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

Last Name: First Name: Cornell NetID, all caps: CS 1110 Regular Prelim 1 Solutions March 2018

CISC 1600, Lab 3.1: Processing

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

n Specifying what each method does q Specify it in a comment before method's header n Precondition q Caller obligation n Postcondition

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

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

In addition to the correct answer, you MUST show all your work in order to receive full credit.

CS Lecture 19: Loop invariants

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

Lecture 18. Classes and Types

COMP-520 GoLite Tutorial

CS 1110 Final Solutions May 2017

Lecture 4. Defining Functions

Structure and Interpretation of Computer Programs

Control Flow: Loop Statements

15-110: Principles of Computing, Spring 2018

CS 455 Final Exam Fall 2016 [Bono] December 13, 2016

All program statements you write should be syntactically correct. Partial credit is not guaranteed with incorrect use of syntax.

Lecture 21. Programming with Subclasses

CISC 1600 Lecture 3.1 Introduction to Processing

TUPLES AND RECURSIVE LISTS 5

Prelim 2 Solution. CS 2110, November 19, 2015, 5:30 PM Total. Sorting Invariants Max Score Grader

Structure and Interpretation of Computer Programs

CSE wi Midterm Exam 2/8/18 Sample Solution

Review 2. Classes and Subclasses

MEMOIZATION, RECURSIVE DATA, AND SETS

CISC 1600, Lab 2.1: Processing

Structure and Interpretation of Computer Programs

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm 1 CSC148H1F L0201 (Liu)

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Transcription:

CS 0 Final, December 7th, 204 SOLUTION This 50-minute exam has 8 questions worth a total of 00 points. Scan the whole test before starting. Budget your time wisely. Use the back of the pages if you need more space. You may tear the pages apart; we have a stapler at the front of the room. It is a violation of the Academic Integrity Code to look at any exam other than your own, look at any reference material, or otherwise give or receive unauthorized help. You will be expected to write Python code on this exam. We recommend that you draw vertical lines to make your indentation clear, as follows: def foo(): if something: do something do more things do something last Unless you are explicitly directed otherwise, you may use anything you have learned in this course. Question Points Score 2 2 0 3 2 4 8 5 2 6 2 7 8 8 6 Total: 00 The Important First Question:. [2 points] Write your last name, first name, netid, and lab section at the top of each page.

Throughout this exam, there are several questions on sequences (strings, lists, and tuples). All sequences support slicing. In addition, you may find the following expressions below useful (though not all of them are necessary). Expression Description len(s) Returns: number of elements in sequence s; it can be 0. x in s Returns: True if x is an element of sequence s; False otherwise. s.index(x) Returns: index of the FIRST occurrence of x in s. Raises a ValueError if x is not found. x.append(a) (Lists Only) Adds a to the end of list x, increasing length by. x.remove(a) (Lists Only) Removes first occurrence of a in x, decreasing length by. x.extend(y) (Lists Only) Appends each element in t to the end of list x, in order. x.insert(i,y) (Lists Only) Inserts y at position i in list x. Elements after position i are shifted to the right. 2. [0 points total] Poutporri (a) [2 points] What is the difference between a statement and an expression? A statement is a command to do something. Each line in a function definition should be a statement. An expression represents a value. Python will evaluate an expression as part of a command, but it is not a command by itself. (b) [3 points] Execute the three statements below. What is printed out? Explain your answer. >>> a = [,2] True >>> b = a[:] False >>> print (a == b) >>> print (a is b) The operator == compares the contents of the lists while is compares the folder ids. Since slicing makes a copy, a and b are different folders. (c) [3 points] Below are three expressions. For each one, write its value. If evaluation leads to an error, just say BAD (do not tell us the exception). 3/2 True or (5/0 < ) (5/0 < ) or True (int division) True BAD (d) [2 points] Is the following definition legal? Why or why not? (abs is built into Python) def absmax(x,y=0,z): """Returns: the maximum absolute value of x, y, and z. Precondition: x, y, and z are numbers (int or float)""" return max(abs(x),abs(y),abs(z)) It is illegal. You cannot have parameters without defaults (e.g. z) after a parameter with a default (e.g. y=0). Page 2

3. [2 points total] Testing and Error Handling (a) [5 points] Consider the following function from lab. def unique(lst): """Returns: The number of unique elements in the list. Example: unique([, 5, 2, 5]) evaluates to 3. Precondition: lst is a list on ints (could be empty).""" Do not implement this function. In the space below,provide at least four different test cases to verify that this function is working correctly. For each test case provide: () the function input, (2) the expected output, and (3) an explanation of what makes this test significantly different. As with all test cases, we look at the preconditions to determine different enough. There are a lot of possible answers for this problem. Below were four we were thinking of. Inputs Output Reason lst=[] 0 Empty list lst=[,2,3] 3 No duplicates lst=[,2,2] 2 One set of duplicates lst=[,2,2,3,3] 3 Multiple sets of duplicates (b) [7 points] Below are two function definitions using asserts and try-except. Write out the series of print statements displayed for each of the given function calls. def first(n): print 'Start first' try: second(n) print 'In first try' except: print 'In first except' print 'Done first' def second(n): print 'Start second' try: assert n <= 0, 'is not <= 0' print 'In second try' except: print 'In second except' assert n >= 0, 'not >= 0' print 'Done second' Function Calls: i. first(-) 'Start first' 'Start second' 'In second try' 'In first except' 'Done first' ii. first() 'Start first' 'Start second' 'In second except' 'Done second' 'In first try' 'Done first' Page 3

Last Name: First: Netid: Section 4. [8 points] Classes and Subclasses For the next two questions, you will be working with a new class called GPanel. The class is a subclass of GRectangle from Assignment 7. This class is very similar to an important class in Java that you will see if you continue on to CS 20. A GPanel is just a GRectangle that can contain other instances of GRectangles (which p can include objects that are GImage itself p2 p3 a subclass of GRectangle or even GPanel). q2 For example, in the image to the right, the GPanel p contains the GRectangle p2, the q GImage p3, and the GPanel p4. Furthermore, the GPanel p4 contains the GRectangle p5 and the GImage p6. The points q, q2, and p4 q3 are part of the next question, and not important just yet. p5 p6 On the next page, you will implement the q3 class GPanel. We have provided all of the specifications. We have also provided most of the method headers; only init has an incomplete header. You are to implement all methods and assert all preconditions. In order to implement this class, you will need to remember the attributes and methods of GRectangle. They are as follows. Attribute x y width height linecolor fillcolor Invariant float float float > 0 float > 0 instance of RGB instance of RGB Method contains(x,y) draw(view) Description Position of left side. Position of bottom edge. Distance from left side to right side. Distance from bottom edge to top edge. Color of rectangle border. Color of rectangle interior. Description Returns: True if the point (x,y) is in the rectangle; False otherwise Draws the rectangle to the specified GView instance view. There are no hidden attributes or methods that you are aware of. You should also avoid using attributes that you might have remembered from Assignment 7, but are not listed in the tables above (you will not need them). Finally, recall how the constructor for GRectangle works. You provide it with a list of keyword arguments that initialize various attributes. For example, to create a red square anchored at (0,0), use the constructor call GRectangle(x=0,y=0,width=0,height=0,fillcolor=colormodel.RED) The constructor for GPanel does not work this way. Please read its specification carefully. Page 4

from game2d import * import colormodel class GPanel(GRectangle): """"Instances are a panel that can store GRectangles (including other GPanels). INSTANCE ATTRIBUTES (in addition to those inherited from GRectangle): _contents [list of GRectangle (or subclass of GRectangle) objects].""" def addcontents(self,rect): """Adds the GRectangle (or subclass of GRectangle) rect to _contents. Precondition: rect is an instance of GRectangle, and is contained inside of the GPanel (left is >= panel s left, right is <= panel s right and so on).""" assert isinstance(rect,grectangle) assert rect.x >= self.x and rect.y >= self.y assert rect.x+rect.width <= self.x+self.width assert rect.y+rect.height <= self.x+self.height self._contents.append(rect) def removecontents(self,rect): """Removes the GRectangle (or subclass of GRectangle) rect from _contents. Precondition: rect is an element of _contents.""" assert rect in self._contents self._contents.remove(rect) def clear(self): """Removes all elements from _contents""" self._contents = [] def getcontents(self): """Returns: a COPY of the list of GRectangles in this GPanel. The GRectangles do not need to be copied; only the list.""" return self._contents[:] def init ( self, x, y, w, h, color=colormodel.white ): # FILL IN """Creates a new GPanel of the given dimensions and color. Parameters x and y specify the bottom left corner of the panel. Parameters w and h are the width and height. Parameter color is the fillcolor. A new GPanel has no GRectangles stored inside it. Precondition: x, y, w, and h are floats with w, h > 0. color is an instance of colormodel.rgb; its default value is colormodel.white.""" assert type(x) == float and type(y) == float assert type(w) == float and type(h) == float assert w > 0 and h > 0 assert isinstance(color,colormodel.rgb) GRectangle. init (self,x=x,y=y,width=w,height=h,fillcolor=color) self._contents = [] Page 5

(Continued from Previous Page) def draw(self,view): """Draws this GPanel AND ITS CONTENTS to the parameter view. The drawing order is important for this method. First it draws the GPanel itself. Then it draws all of the contents, in the order that they are given in the list _contents (so items at the end of the list are on top). Precondition: view is an instance of GView.""" assert isinstance(view,gview) GRectangle.draw(self,view) for item in self._contents: item.draw(view) 5. [2 points] Recursion and Iteration We need one more method in GPanel. This method takes a point (x,y) and returns the top most element containing that point. For example, in the image in question 4, p.selected(q.x,q.y) returns p, p.selected(q2.x,q2.y) returns p2, and p.selected(q3.x,q3.y) returns p5. Hint: You will need both recursion and iteration. You do not need to assert the precondition. def selected(self,x,y): """Returns: the topmost GRectangle containing the point (x,y) If (x,y) is not inside this GPanel, it returns None. Otherwise, it returns the top most item (which might be the GPanel itself) containing (x,y). Since objects are drawn back to front, top most is the LAST item in _contents that contains (x,y). Furthermore, if that item is itself a GPanel, then you must check the contents of that GPanel as well. Precondition: x and y are floats.""" if not self.contains(x,y): return None choice = self for item in self._contents: if item.contains(x,y): if isinstance(item,gpanel): else: choice = item.selected(x,y) choice = item return choice Page 6

6. [2 points] 2-Dimensional Lists Recall the class GRectangle from Assignment 7 and the previous two problems. In Assignment 7, you had to lay the bricks out on the screen in a pattern. You are going to do something similar here; the function make_bricks creates a 2-dimensional list of bricks arranged as shown to the right. In writing this function, keep the following in mind. There are m columns and rows of squares. In the example above, m = 8. Each square has side length SIZE, and there is no space between them. The origin is in the bottom-left corner. x increases to the right; y increases upward. Each row in the list contains a single row of bricks, starting at the bottom. Squares in columns and rows 0 and m- have fillcolor colormodel.pink. The bottom, left-most inner square has fillcolor colormodel.red Inner squares alternate in a checkerboard of colormodel.red and colormodel.green. def make_bricks(m): """Returns: a 2-D list of GRectangle objects with the properties above. Precondition: m > 0 is an int""" bricks = [] for r in range(m): row = [] for c in range(m): b = GRectangle(x=c*SIZE, y=r*size, width=size, height=size) if r == 0 or r == m- or c == 0 or c == m-: b.fillcolor = colormodel.pink elif r+c % 2 == 0: else: b.fillcolor = colormodel.red b.fillcolor = colormodel.green row.append(b) bricks.append(row) return bricks Page 7

7. [8 points] Call Frames The code to the right is the Fibonacci function from class; line numbers are labelled in red. On this page and the next, diagram the statement r = (2). Draw the contents of the call stack and global space, but not heap space. You need a new diagram every time a frame is added or erased, or an instruction counter changes. We have done the first step for you. There are eleven more diagrams to draw. Please order your answer according to the numbers given. You may write unchanged if a space does not change. def (n) if n == 0 or n == : return 2 one = (n-) 3 two = (n-2) 4 return one+two 5 Call Frames Global Space Call Frames Global Space 3 3 2 n 3 3 4 n 3 2 4 5 one n Page 8

Call Frames Global Space Call Frames Global Space 4 6 5 9 one one two n 0 4 7 0 one one two 2 2 n 0 8 one one r 2 two 2 n 0 8. [6 points total] Loop Invariants On the next page are two variations of the Dutch National Flag algorithm from class. The one on the left has been completed for you. The second algorithm is identical to the first except that it has a different loop invariant. It is currently missing the code for initialization, the loop condition, and the body of the loop (all other code is provided). (a) [3 points] Draw the horizontal notation representation for the loop invariant on the left. h t i j k b < 0??? = 0 > 0 Page 9

(b) [3 points] Draw the horizontal notation representation for the loop invariant on the right. h i j t k b < 0 = 0??? > 0 (c) [0 points] Add the missing code to the function on the right. Like the function on the left, you may use the helper function swap(b,n,m) to swap two positions in the list. It is not enough for your code to be correct. To get credit, you must satisfy the loop invariant. def dnf(b,h,k): """Returns: Divisions i, j of dnf Pre: h, k are positions in list b.""" # Make invariant true at start t = h j = k+ i = k+ # inv: b[h..t-] < 0, b[t..i-]???, # b[i..j-] = 0, and b[j..k] > 0 def dnf(b,h,k): """Returns: Divisions i, j of dnf Pre: h, k are positions in list b.""" # Make invariant true at start i = h j = h t = k+ # inv: b[h..i-] < 0, b[i..j-] = 0, # b[j..t-]???, and b[t..k] > 0 while t < i: if b[i-] < 0: swap(b,i-,t) t= t+ elif b[i-] == 0: i= i- else: swap(b,i-,j-) i= i- j= j- while t > j: if b[j] < 0: swap(b,i,j) i= i+ j= j+ elif b[j] == 0: j = j+ else: swap(b,j,t-) t = t- # post: b[h..i-] < 0, b[i..j-] = 0, # and b[j..k] > 0 return (i,j) # post: b[h..i-] < 0, b[i..j-] = 0, # and b[j..k] > 0 return (i,j) Page 0