Structure and Interpretation of Computer Programs

Similar documents
Structure and Interpretation of Computer Programs Fall 2016 Midterm 2

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Spring 2019 Midterm 2

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Fall 2015 Midterm 2

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Fall 2015 Midterm 1

Structure and Interpretation of Computer Programs Summer 2015 Midterm 2

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Spring 2015 Midterm 2

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Summer 2015 Midterm 1

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Spring 2017 Mock Midterm 1

Structure and Interpretation of Computer Programs Summer 2014 Midterm 1

Structure and Interpretation of Computer Programs Summer 2014 Midterm 2

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Spring 2016 Test 1

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Examination Questions Midterm 2

Structure and Interpretation of Computer Programs

20 Some terminology regarding trees: Parent node: A node that has branches. Parent nodes can have multiple branches.

Final Exam Solutions. Structure and Interpretation of Computer Programs. Fall 2011 /12 /16 /12 /18 /10 /12 /80 INSTRUCTIONS

TREES AND ORDERS OF GROWTH 7

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections)

Midterm 2 Review Fall 2017 October 13, Lists & Tree Recursion. Instructions

cs61amt2_4 CS 61A Midterm #2 ver March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name

CS251-SE1. Midterm 2. Tuesday 11/1 8:00pm 9:00pm. There are 16 multiple-choice questions and 6 essay questions.

LINKED LISTS AND MIDTERM REVIEW

TREES AND ORDERS OF GROWTH 7

Structure and Interpretation of Computer Programs

Midterm solutions. n f 3 (n) = 3

Midterm #1 Fall minutes

MIDTERM EXAMINATION Douglas Wilhelm Harder EIT 4018 x T09:30:00P1H20M Rooms: RCH-103 and RCH-302

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

CS 61A Midterm #2 ver March 2, 1998 Exam version: A. Your name. login: cs61a- Discussion section number. TA's name

Introduction to Algorithms March 12, 2008 Massachusetts Institute of Technology Spring 2008 Professors Srini Devadas and Erik Demaine Quiz 1

Midterm Exam 1 Solutions

Lecture #21: Search Trees, Sets. Last modified: Tue Mar 18 18:15: CS61A: Lecture #21 1

Guerrilla Section 5: Object Oriented Programming, Nonlocal & Mutable Trees

Quiz 1 Solutions. Asymptotic growth [10 points] For each pair of functions f(n) and g(n) given below:

Analysis of Algorithms

CPS 231 Exam 2 SOLUTIONS

Computer Science Foundation Exam

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators)

IMPORTANT: Circle the last two letters of your class account:

TREES AND ORDERS OF GROWTH 8

: Fundamental Data Structures and Algorithms. June 06, 2011 SOLUTIONS

CSL 201 Data Structures Mid-Semester Exam minutes

Structure and Interpretation of Computer Programs

CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm

Technical University of Denmark

CSE332 Summer 2010: Midterm Exam Sample Solutions

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

CS 540: Introduction to Artificial Intelligence

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

CSE 332 Spring 2014: Midterm Exam (closed book, closed notes, no calculators)

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

STREAMS, ITERATORS, AND BINARY TREES 10

CS 61A Orders of Growth & Linked Lists Spring 2018 Discussion 6: March 7, Warmup

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

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

CS 2316 Exam 4 Fall 2011

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22

LINKED LISTS AND MIDTERM REVIEW 6

Midterm Practice Exam Sample Solutions

Multiple-choice (35 pt.)

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

B-Trees. Based on materials by D. Frey and T. Anastasio

PROBLEM 1 : (And the winner is...(12 points)) Assume you are considering the implementation of a priority queue that will always give you the smallest

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1

University of Toronto Department of Electrical and Computer Engineering. Midterm Examination. ECE 345 Algorithms and Data Structures Fall 2010

EXAM PREPARATION SECTION 1

CS 216 Exam 1 Fall SOLUTION

Problem Set 6 Due: 11:59 Sunday, April 29

Transcription:

CS 61A Fall 016 Structure and Interpretation of Computer Programs Midterm Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except one hand-written 8.5 11 crib sheet of your own creation and the official CS 61A study guides. Mark your answers on the exam itself. We will not grade answers written on scratch paper. Last name First name Student ID number CalCentral email (_@berkeley.edu) TA Name of the person to your left Name of the person to your right All the work on this exam is my own. (please sign)

1. (8 points) Halloween For each of the expressions in the table below, write the output displayed by the interactive Python interpreter when the expression is evaluated. The output may have multiple lines. If an error occurs, write Error, but include all output displayed before the error. The Link class appears on page of the midterm study guide. The first two rows have been provided as examples. Recall: The interactive interpreter displays the value of a successfully evaluated expression, unless it is None. Assume that you have started python3 and executed the following statements: class Party : guests = Link. empty init (self, time ): Party. guests = Link ( time +1, Party. guests ) attend ( self ): self. guests. rest = Link ( self. guests. rest ) self. guests class Costume ( Party ): init (self, bow, tie ): Party. guests. rest = Link ( bow ) self.ie = Link ( self ) attend ( self ): print ( repr ( self.ie )) Party. attend = lamb self : Party ( 9). guests repr ( self ): print ( Nice ) Costume Expression Link(1, Link.empty) Link(1, Link()) Party(1).guests Party(3).attend() Costume(5, 6).attend() Party(7).attend() Interactive Output Link(1) Link(1, Link()) Link() Link(4, Link(Link())) Nice Link(Costume) Link(10, Link(8, Link(4, Link(5))))

Name: 3. (8 points) A List with a Twist Fill in the environment diagram that results from executing the code below until the entire program is finished, an error occurs, or all frames are filled. You may not need to use all of the spaces or frames. A complete answer will: Add all missing names and parent annotations to frames. Add all missing values created or referenced during execution. Show the value for each local frame. Use box-and-pointer notation for list values. You do not need to write index numbers or the word list. 1 3 4 5 6 7 8 9 10 11 1 lamb = '' (): lamb(lamb): nonlocal (nk): = nk + [''].append(nk[0:]) nk.pop() (lamb) ([[1], ]) + 3 (lamb : (lamb)) Global frame lamb '' f1: [parent= ] Global lamb func () [parent=g] func (nk) [parent=f3] func lamb(lamb) [parent=f1] Return Value 5 f: λ [parent= ] Global Return Value None f3: lamb [parent= ] f1 lamb '' Return Value None list 0 1 f4: [parent= ] f3 nk list 0 1 list 0 1 '' list 0 1 3 Return Value

4 3. (6 points) Return Policy Implement quota, which takes a one-argument function f and a non-negative integer limit. The function it s has the same behavior as f, except that each value is only ed up to limit times. After that, the function s an Over quota message instead, and the limit is decreased by 1 for future calls. quota (f, limit ): A decorator that limits the number of times a value can be ed. >>> square = lamb x: x * x >>> square = quota ( square, 3) >>> square (6) # 1 st call with value 36 36 >>> [ square (5) for x in range ( 3)] # 3 calls when the limit is 3 [5, 5, 5] >>> square (5) # 4 th call with value 5 Over quota! Limit is now >>> square ( -6) # nd call with value 36 36 >>> square ( -6) # 3 rd call when the limit is Over quota! Limit is now 1 >>> square (7) # 1 st call when the limit is 1 49 >>> square (5) # 5 th call with value 5 Over quota! Limit is now 0 values = [] limited (n): nonlocal limit y = f(n) count = len ([ x for x in values if x == y]) values. append (y) if count < limit : y limit = limit - 1 Over quota! Limit is now + str ( limit ) limited

Name: 5 4. (6 points) A Classy Election Implement the VotingMachine and Ballot classes based on the doctest below. The voting machine must determine which choice has the most votes (the winner) and detect if a ballot is used more than once. In case of a tie, the winner among choices with maximal votes is the one that most recently received a vote. Ballot.vote takes a string, and a VotingMachine must handle an arbitrary number of choices. class VotingMachine : A machine that creates and records ballots. >>> machine = VotingMachine (4) >>> a, b, c, d = machine. ballots >>> d. vote ( Bruin ) Bruin is winning >>> b. vote ( Bruin ) Bruin is winning >>> c. vote ( Bear ) Bear is losing >>> a. vote ( Bear ) Bear is winning >>> c. vote ( Tree ) Fraud : multiple votes from the same ballot! >>> machine. winner Bear init (self, k): self. ballots = [ Ballot ( self ) for i in range (k)] self. votes = {} record ( self, ballot, choice ): if ballot. used : Fraud : multiple votes from the same ballot! ballot. used = True self. votes [ choice ] = self. votes. get ( choice, 0) + 1 if max ( self. votes. values ()) > self. votes [ choice ]: choice + is losing else : self. winner = choice choice + is winning class Ballot : used = False init (self, machine ): self. machine = machine vote (self, x): self. machine. record (self, x)

6 5. (6 points) Trick or Tree Implement path, which takes a linked list s and a Tree instance t. It s whether s is a path from the root of t to some leaf. The Tree and Link classes are on page of the midterm study guide. Restrictions: You may not call the built-in len function on a linked list or invoke its len method. You may not apply element selection (e.g., s[]) on a linked list or invoke its getitem method. from tree import * from link import * path (s, t): Return whether Link S is a path from the root to a leaf in Tree T. >>> t = Tree (1, [ Tree (), Tree (3, [ Tree (4), Tree (5)]), Tree (6)]) >>> a = Link (1, Link (3, Link (4))) # A full path >>> path (a, t) True >>> b = Link (1, Link ( 3)) # A partial path >>> path (b, t) False >>> c = Link (1, Link (, Link ( 7))) # A path and an extra value >>> path (c, t) False >>> d = Link (3, Link ( 4)) # A path of a branch >>> path (d, t) False if s is Link. empty or t. root!= s. first : False if t. is_leaf () and s. rest is Link. empty : True any ([ path (s.rest, b) for b in t. branches ])

Name: 7 6. (6 points) Left it Right There (a) (4 pt) Implement binary, which takes a list s of unique integers. It s a binary search tree containing all of those integers, represented as a BTree instance or BTree.empty. The values in any path of this tree must appear in the same order as they did in s. The BTree class is on page of the midterm study guide. from tree import * binary (s): Construct a binary search tree from S for which all paths are in order. >>> binary ([3, 5, 1]) BTree (3, BTree (1), BTree (5)) >>> binary ([4, 3, 7, 6,, 9, 8]) BTree (4, BTree (3, BTree ()), BTree (7, BTree (6), BTree (9, BTree (8)))) assert len ( s) == len ( set ( s)), All elements of s should be unique if not s: BTree. empty root = s [0] left = [ x for x in s if x < root ] right = [ x for x in s if x > root ] BTree (root, binary ( left ), binary ( right )) (b) (1 pt) Circle the Θ expression that describes the smallest possible height of the tree ed by binary(s) for a list s of length n. The height of a tree is the length of the longest path from its root to a leaf. Θ(1) Θ(log n) Θ(n) Θ(n ) Θ( n ) None of these (c) (1 pt) Circle the Θ expression that describes the largest possible height of the tree ed by binary(s) for a list s of length n. The height of a tree is the length of the longest path from its root to a leaf. Θ(1) Θ(log n) Θ(n) Θ(n ) Θ( n ) None of these

8 7. (10 points) Summer Camp (a) (6 pt) Implement sums, which takes two positive integers n and k. It s a list of lists containing all the ways that a list of k positive integers can sum to n. Results can appear in any order. sums (n, k): Return the ways in which K positive integers can sum to N. >>> sums (, ) [[1, 1]] >>> sums (, 3) [] >>> sums (4, ) [[3, 1], [, ], [1, 3]] >>> sums (5, 3) [[3, 1, 1], [,, 1], [1, 3, 1], [, 1, ], [1,, ], [1, 1, 3]] if k == 1: [[n]] y = [] for x in range (1, n): # range (1, n-k +1) is OK y. extend ([s + [x] for s in sums (n-x, k -1)]) y OR if n == 0 and k == 0: [[]] y = [] for x in range (1, n +1): y. extend ([s + [x] for s in sums (n-x, k -1)]) y (b) (4 pt) Why so many lines? Implement f and g for this alternative version of the sums function. f = lamb x, y: (x and [[x] + z for z in y] + f(x -1, y)) or [] sums (n, k): Return the ways in which K positive integers can sum to N. >>> sums (, ) [[1, 1]] >>> sums (4, ) [[3, 1], [, ], [1, 3]] >>> sums (5, 3) [[3, 1, 1], [,, 1], [, 1, ], [1, 3, 1], [1,, ], [1, 1, 3]] g = lamb w: (w and f(n, g(w -1))) or [[]] [v for v in g(k) if sum (v) == n]