CS 1110 Final Exam, May 2018

Similar documents
CS 1110 Final Exam Solutions May 2018

CS 1110 Final, May 2017

CS 1110 Regular Prelim 1, March 14th, 2017

CS 1110 Prelim 1, March 2018

CS 1110 Prelim 2 April 22, 2014

CS 1110 Prelim 2 April 26th, 2016

CS 1110 Final Exam May 9th, 2013 SOLUTIONS

CS 1110 Prelim 2 Solutions April 2018

CS 1110 Prelim 2 November 14th, 2013

CS 1110 Prelim 1 March 15th, 2016

CS 1110 Prelim 1 March 7th, 2013

CS 1110 Prelim 1 October 4th, 2012

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

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

CS 1110 Prelim 2 November 13th, 2014

CS 1110 Prelim 1 October 17th, 2013

CS 1110 Prelim 2 November 6th, 2012

CS 1110 Prelim 2 November 12th, 2015

CS 1110 Prelim 2 November 10th, 2016

CS 1110 Final, December 16th, 2013

CS 1110 Prelim 1 March 10, 2015

CS 1110 Prelim 1 October 15th, 2015

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

CS 1110 Prelim 2 November 12th, 2015

CS 1110 Final, December 16th, 2013

CS 1110 Final Exam Solutions May 15th, 2014

PREPARING FOR PRELIM 2

PREPARING FOR THE FINAL EXAM

CS 1110 Prelim 2 April 21, 2015

CS 1110 Final Solutions May 2017

CS 1110 Prelim 1 October 12th, 2017

Review 2. Classes and Subclasses

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Lecture 17: Classes (Chapter 15)

CS Prelim 2 Review Fall 2017

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

Lecture 17: Classes (Chapter 15)

CS 1110: Introduction to Computing Using Python Loop Invariants

CS 1110 Final, December 7th, 2017

PREPARING FOR PRELIM 1

CS Prelim 2 Review Fall 2018

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

CS 111X - Spring Final Exam - KEY

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

Student Number: Instructor: Brian Harrington

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

CS Prelim 2 Review Fall 2015

CS Prelim 2 Review Fall 2014

CS 111X - Fall Test 1

CSC148 Recipe for Designing Classes

COS 126 General Computer Science Spring Written Exam 1

Lists, loops and decisions

Prelim 1. CS 2110, 14 March 2017, 7:30 PM Total Question Name Short answer. OO Recursion Loop invariants Max Score Grader

ASYMPTOTIC COMPLEXITY

Structure and Interpretation of Computer Programs

Prelim 1. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants

First name (printed): a. DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

CS 4620 Midterm, March 21, 2017

Overview of List Syntax

CS 1301 Exam 1 Fall 2014

Lecture 19: Subclasses & Inheritance (Chapter 18)

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

PREPARING FOR THE FINAL EXAM

CIS 120 Midterm I October 2, Name (printed): Username (login id):

CS Lecture 19: Loop invariants

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Structure and Interpretation of Computer Programs

Last Name: UTION First Name: SOL Cornell NetID: CS1110. Solution: CS 1110 Prelim 2 April 26, 2016

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

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

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

CS 115 Lecture 8. Selection: the if statement. Neil Moore

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

CS Prelim 2 Review Fall 2012

CSE 131S Introduction to Computer Science Summer SON Exam I

CSC148: Week 1

Prelim 1. CS 2110, March 15, 2016, 5:30 PM Total Question Name True False. Short Answer

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

a declaration of class name, and a class docstring

Refreshing last time

Final Exam. COMP Summer I June 26, points

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

UNIVERSITY OF TORONTO Faculty of Arts and Science

CS 1301 Exam 1 Fall 2010

EXAMINATION INSTRUCTIONS

ASYMPTOTIC COMPLEXITY

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

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

CS112 Spring 2012 Dr. Kinga Dobolyi. Exam 2. Do not open this exam until you are told. Read these instructions:

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

Prelim 1. CS 2110, March 15, 2016, 7:30 PM Total Question Name True False. Short Answer

CS 1301 Exam 1 Fall 2014

Prelim 2. CS 2110, 5:30 PM, November 17, 2016

You may not share any information or materials with classmates during the exam and you may not use any electronic devices.

Student Performance Q&A:

Lecture 10: Lists and Sequences

Transcription:

Last Name: First Name: Cornell NetID, all caps: CS 1110 Final Exam, May 2018 This 150-minute exam has 7 questions worth a total of 79 points. You may tear the pages apart; we have staplers. You may use any Python introduced so far in this course, but not Python constructs that we have not introduced. When a question asks for a particular technique to be used, do not expect to receive credit for questions based on a different technique. For example, if we ask you to make effective use of recursion, your solution must be fundamentally based on recursion, even if a recursion-less for-loop would also solve the problem. The second page of this exam gives you the specifications for some useful functions and methods. 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 It is a violation of the Academic Integrity Code to look at any exam other than your own, to look at any other reference material, or to otherwise give or receive unauthorized help. We also ask that you not discuss this exam with students who are scheduled to take a later makeup. Academic Integrity is expected of all students of Cornell University at all times, whether in the presence or absence of members of the faculty. Understanding this, I declare I shall not give, use or receive unauthorized aid in this examination. Signature: Date

s.find(substr) Returns: index of first occurrence of string substr in string s (-1 if not found) s.strip() Returns: copy of string s where all whitespace has been removed from the beginning and the end of s. Whitespace not at the ends is preserved. s.split(sep) Returns: a list of the words in string s, using sep as the word delimiter (whitespace if sep not given) s.join(slist) Returns: a string that is the concatenation of the strings in list slist separated by string s s[i:j] Returns: if i and j are non-negative indices and i j-1, a new string containing the characters in s from index i to index j-1, or the substring of s starting at i if j len(s) lt.insert(i,item) Insert item into list lt at position i lt.append(item) Adds item to the end of list lt lt.count(item) Returns: count of how many times item occurs in list list(range(n)) Returns: the list [0.. n-1] lt.remove(item) Removes the first occurrence of item from list lt; raises an error if item not found. lt.index(item) Returns: index of first occurrence of item in list lt; raises an error if item is not found. (There s no find for lists.) lt[i:j] Returns: A new list[lt[i], lt[i+1],..., lt[j-1]] under ordinary circumstances. Returns [] if i and j are not both sensible indices. lt.pop(i) Returns: element of list lt at index i and also removes that element from the list lt. Raises an error if i is an invalid index. list(map(func, lt)) isinstance(o, c) Returns: A list obtained by applying function func to each element in list lt and concatenating the results of each application. Returns: True if o is an instance of class c, False otherwise. Question Points Score 1 18 2 14 3 13 4 5 5 12 6 6 7 11 Total: 79 Page 2

1. Object Diagramming and Terminology. (a) [10 points] The questions on the right pertain to the code on the left. Some questions may have multiple correct answers. Write down only one answer. 1 class A(): 2 x = 1 3 4 def init (self, n): 5 self.y = n 6 A.x += 1 7 8 def p(self): 9 print(self.y) 10 self.y += 3 11 self.r() 12 13 def r(self): 14 self.y += 2 15 print(self.y) 16 17 class B(A): 18 x = 10 19 20 def init (self, n): 21 super(). init (n) 22 sum = self.y + B.x 23 self.m = sum 24 25 def r(self): 26 self.y += self.x 27 print(self.m) 28 29 a = A(1) 30 b = B(2) an object folder is created when Python executes line a class folder is created when Python executes line an object attribute is created on line a class attribute is created on line a superclass definition begins on line a class method definition begins on line an attribute definition that overrides another begins on line a method definition that overrides another begins on line a local variable is created on line a global variable is created on line Page 3

This code is copied from the previous page with two additional lines of code. It runs error-free. 1 class A(): 2 x = 1 3 4 def init (self, n): 5 self.y = n 6 A.x += 1 7 8 def p(self): 9 print(self.y) 10 self.y += 3 11 self.r() 12 13 def r(self): 14 self.y += 2 15 print(self.y) 16 17 class B(A): 18 x = 10 19 20 def init (self, n): 21 super(). init (n) 22 sum = self.y + B.x 23 self.m = sum 24 25 def r(self): 26 self.y += self.x 27 print(self.m) 28 29 a = A(1) 30 b = B(2) 31 a.p() 32 b.p() (b) [4 points] What will be printed when Python executes line 31? (c) [4 points] What will be printed when Python executes line 32? Page 4

2. Object Creation and Foor Loops. Consider the following code: class MenuItem(): """An instance represents an item on a menu.""" def init (self, name, is_veggie, price): """A new menu item called name with 3 attributes: name: a non-empty str, e.g. 'Chicken Noodle Soup' is_veggie: a Bool indicating vegetarian or not price: an int > 0 """ self.name = name self.is_veggie = is_veggie assert price > 0 self.price = price class LunchItem(MenuItem): """An instance represents an item that can also be served at lunch""" def init (self, name, is_veggie, price, lunch_price): """A menu item with one additional attribute: lunch_price: an int > 0 and <= 10""" super(). init (name, is_veggie, price) assert lunch_price > 0 assert lunch_price <= 10 self.lunch_price = lunch_price (a) [2 points] Write a python assignment statement that stores in variable item1 the ID of a new MenuItem object whose name is Tofu Curry, a vegetarian dish costing 24 dollars. (b) [2 points] Write a python assignment statement that stores in variable item2 the ID of a new LunchItem object whose name is Hamburger, a non-vegetarian dish that costs 12 dollars, but only 8 dollars at lunch. (c) [2 points] Class Invariants. Lunch should never cost more than 10 dollars. The init method prevents this. Write a line of python that shows how this invariant can still be broken. You may use any of the global variables you created from the previous parts. Page 5

The same code has been copied to this page for your convenience: class MenuItem(): """An instance represents an item on a menu.""" def init (self, name, is_veggie, price): """A new menu item called name with 3 attributes: name: a non-empty str, e.g. 'Chicken Noodle Soup' is_veggie: a Bool indicating vegetarian or not price: an int > 0 """ self.name = name self.is_veggie = is_veggie assert price > 0 self.price = price class LunchItem(MenuItem): """An instance represents an item that can also be served at lunch""" def init (self, name, is_veggie, price, lunch_price): """A menu item with one additional attribute: lunch_price: an int > 0 and <= 10""" super(). init (name, is_veggie, price) assert lunch_price > 0 assert lunch_price <= 10 self.lunch_price = lunch_price (d) [8 points] For Loops. Make effective use of a for-loop to write the body of the function audit menu according to its specification. def audit_menu(the_menu): """Performs an audit of each LunchItem on the_menu, making sure that each lunch_price is never more than 10 dollars. A lunch_price of 11 dollars is changed to 9. An item whose lunch_price is more than 11 is too expensive to be offered at lunch; it must be replaced with a new, equivalent MenuItem (that has no lunch price). Items that are not LunchItems are unchanged. Modifies the_menu; does not create or return a new menu/list the_menu: possibly empty list of MenuItem """ Page 6

3. [13 points] String processing. Complete the function below so that it obeys its specification. Sample inputs, the value of an important local variable, and desired outputs are given at the bottom of the page. def after_at(s): """Returns a list of every non-empty sequence of non-space characters that follows an @ in s. The elements should be ordered by occurrence in s, and there should be no repeats. Pre: s is a string, possible empty. """ temp = s.split('@') if len(temp) == 1: # There were no @s in s. return [] afters_list = temp[1:] # Drop stuff before 1st @. See table at bottom of page. # DON'T use split. (It sometimes calls strip(), which you don't want here.) # Hint: for each item in afters_list, find where its first space is. s afters list (local variable) return value '@bill @ted meet @ the Circle K' ['bill ', 'ted meet ', ' the Circle K'] ['bill', 'ted'] 'meet @ the Circle K @Bill@Ted' [' the Circle K ', 'Bill', 'Ted'] ['Bill', 'Ted'] 'hi' [] [] '@martha @Martha @martha' ['martha ', 'Martha ', 'martha'] ['martha', 'Martha'] 'The symbol du jour is an @' [''] [] 'The symbol du jour is an @!' ['!'] ['!'] Page 7

4. [5 points] While Loops. Make effective use of while loops to implement countdown by n. Your solution must use a while loop to receive points. def countdown_by_n(count_from, count_by): """Prints a count down from count_from by count_by. Stops printing before the result goes negative. Note: this function does not return anything. count_from: the number you're counting down from [int] count_by: the amount you're counting down by [int > 0] Examples: coundown_by_n(16, 5) should print: 16 11 6 1 coundown_by_n(21, 7) should print: 21 14 7 0 """ Page 8

5. [12 points] Call Frames. On the right, draw the full call stack as it would look after all of the code on the left has executed. Include crossed-out frames. Do not worry about drawing any variables outside the call frames. 1 def fib(n): 2 sum = 0 3 if n == 0 or n == 1: 4 return 1 5 6 sum += fib(n-1) 7 sum += fib(n-2) 8 return sum 9 10 x = fib(2) Page 9

6. Invariants. Let b be a non-empty list of ints, and splitter be an int. We want a for-loop that swaps elements of b and sets the variable i so that the following postcondition holds: i b <= splitter > splitter Examples: Before After splitter b i b 0 [16, -4, 22] 1 [-4, 22, 16] or [-4, 16, 22] 0 [-10, -20, 15] 2 [-10, -20, 15] or [-20, -10, 15] 0 [-30, -50, -60] 3 any ordering of b works -4 [10, 20, 30] 0 any ordering of b works The code must maintain the following invariant. i k b <= splitter > splitter??? In words, b[0..i-1] are all less than or equal to splitter; b[i..k-1] are all greater than splitter; b[k..len(b)-1] have not yet been processed. (a) [2 points] According to the invariant, should the initialization be i=1? If yes, explain why no credit without correct explanation. If no, give the correct initialization; omit explanation in this case. (b) [4 points] Here is the for-loop header: for k in list(range(len(b))): According to the invariant, is the following the correct and complete for-loop body? (Assume the helper does what the comment says.) if b[k] <= splitter: swap(b, i, k) # Helper that swaps items at position i and k in b i += 1 If yes, explain why no credit without correct explanation. If no, give the correct and complete for-loop body; omit explanation in this case. Page 10

7. [11 points] Recursion. Assume that objects of class Course have two attributes: label [non-empty str]: unique identifying string, e.g., 'CS1110' prereqs [list of Course, maybe empty]: Courses that one must complete before this one. Consider the following header and specification of a non-method function. def requires(c, other_label): """Returns True if Course with label other_label must be taken before c, False otherwise. Pre: c is a Course. other_label is a non-empty string.""" Example intended operation: suppose c1 is a Course with label 'CS1110' and empty prereqs list; c2 is a Course with label 'CS2110' and prereqs list [c1]; c3 is a Course with label 'CS2800' and prereqs list [c1]; c4 is a Course with label 'CS3110' and prereqs list [c2, c3] Then, all of the following should evaluate to True: requires(c4, 'CS2800') requires(c4, 'CS2110') requires(c4, 'CS1110') And all of the following should evaluate to False: requires(c1, 'CS2800') requires(c3, 'CS2800') requires(c4, 'randomstring') While a majority of the lines are correct, there is at least one error in the proposed implementation below. For each error, circle it, write down/explain the correct version, and draw a line between the circle and the corresponding correction. Responses where the correction is wrong may not receive any credit. def requires(c, other_label): # STUDENTS: do NOT alter this header. if len(c.prereqs) <= 1: return False else: for p in prereqs: if p.label == other_label: return True elif requires(other_label, c): return True return False Did you re-read all specs, and check your code works against test cases? Then, have a great summer! Page 11