Structure and Interpretation of Computer Programs

Similar documents
Structure and Interpretation of Computer Programs Summer 2014 Midterm 2

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Summer 2014 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

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

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

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

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

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Spring 2017 Mock Midterm 1

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Structure and Interpretation of Computer Programs

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Summer 2015 Midterm 1

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

CSE341 Spring 2017, Final Examination June 8, 2017

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

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Summer 2015 Midterm 2


CS61A Midterm 2 Review (v1.1)

CSE341 Spring 2017, Final Examination June 8, 2017

Scheme Basics > (butfirst '(help!)) ()

Structure and Interpretation of Computer Programs

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

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

Midterm Exam 1 Solutions

Structure and Interpretation of Computer Programs

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

Intro. Scheme Basics. scm> 5 5. scm>

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

Structure and Interpretation of Computer Programs Spring 2015 Midterm 2

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

CSE341 Autumn 2017, Final Examination December 12, 2017

Structure and Interpretation of Computer Programs Spring 2019 Midterm 2

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

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

Structure and Interpretation of Computer Programs

CS3L Summer 2011 Final Exam, Part 2 You may leave when finished; or, you must stop promptly at 12:20

SCHEME AND CALCULATOR 5b

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

Structure and Interpretation of Computer Programs

Section 1: True / False (2 points each, 30 pts total)

Structure and Interpretation of Computer Programs Fall 2015 Midterm 2

UNIVERSITY OF TORONTO Faculty of Arts and Science

CS 1301 CS1 with Robots Summer 2007 Exam 1

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.

This exam is worth 30 points, or 18.75% of your total course grade. The exam contains

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

This exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions.

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

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

Structure and Interpretation of Computer Programs Fall 2015 Midterm 1

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

Introduction to Spring 2007 Artificial Intelligence Midterm Solutions

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

CS 115 Exam 3, Fall 2011

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

ˆ The exam is closed book, closed calculator, and closed notes except your one-page crib sheet.

CS150 Sample Final. Name: Section: A / B

CONTROL AND ENVIRONMENTS 1

Write a procedure powerset which takes as its only argument a set S and returns the powerset of S.

Structure and Interpretation of Computer Programs

Sample Final Exam Questions

INTERPRETERS AND TAIL CALLS 9

Comp 311: Sample Midterm Examination

Structure and Interpretation of Computer Programs Spring 2016 Test 1

ENVIRONMENT DIAGRAMS AND RECURSION 2

LINKED LISTS AND MIDTERM REVIEW

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

Structure and Interpretation of Computer Programs

CS 314 Principles of Programming Languages. Lecture 16

YOUR NAME PLEASE: *** SOLUTIONS ***

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Structure and Interpretation of Computer Programs

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

Fall 2017 December 4, Scheme. Instructions

The exam is closed book, closed calculator, and closed notes except your one-page crib sheet.

CS 415 Midterm Exam Spring 2002

Transcription:

CS 61A Summer 2014 Structure and Interpretation of Computer Programs Midterm 2 Solutions INSTRUCTIONS ˆ You have 2 hours to complete the exam. ˆ The exam is closed book, closed notes, and closed electronics, except two 8.5 11 cheat sheets, and The Environment Diagram Rules. ˆ Mark your answers ON THE EXAM ITSELF. Answers outside of the space allotted to problems will not be graded. If you are not sure of your answer you may wish to provide a brief explanation. Full name SID Login TA & section time 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) 0. (1 points) Your thoughts?

2 1. (8 points) What will Python output? Include all lines that the interpreter would display. If it would display a function, then write Function. If it would cause an error, write Error. Assume that you have started Python 3 and executed the following. These are entered into Python exactly as written. class Pet : color = " Red " name = " Clifford " def init (self, num_legs ): print ("A new pet!") self. num_ legs = num_ legs def sleep (): print (" Zzzz ") class RubberDuck ( Pet ): color = " Yellow " def init ( self ): self. voice = print (" Quack ") Pet. name = " Daisy " name = " Daffy " self. num_legs = Pet (0). num_legs def debug ( self ): print (" What is wrong?") return self. voice Expression print("ducks are cool!") p = Pet(4) p.self.name p.sleep() q = RubberDuck() Interactive Output Ducks are cool! A new pet! Error: Attribute not found Error: Gave 1 Arg, expected 0 Quack A new pet! p.name + q.name print(q.debug()) DaisyDaisy What is wrong? None

Login: 3 2. (12 points) Environment Diagrams (a) (6 pt) Saturday Morning 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. You may want to keep track of the stack on the left, but this is not required. A complete answer will: ˆ Add all missing names, labels, and parent annotations to all local frames. ˆ Add all missing values created during execution. ˆ Show the return value for each local frame. ˆ The first function created by lambda should be labeled λ 1, the next one should be λ 2, and so on. breakfast = waffles! def saturday(morning):! def breakfast(cereal):! nonlocal breakfast! breakfast = cereal! breakfast(morning)! return breakfast! saturday(lambda morning: \! breakfast)( cereal )! Global frame breakfast saturday waffles func saturday(morning) [p=global] func λ(morning) <line 8> [p=global] f1: saturday [p=global] morning breakfast Stack global! f1! f2! f3! f2: breakfast [p=f1] cereal f3: λ [p=global] morning cereal waffles

4 (b) (6 pt) Box and Pointer Fill in the enviroment 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, labels, and parent annotations to all local frames. ˆ Add all missing values created during execution. This may include more box-and-pointer diagrams. ˆ Show the return value for each local frame. ˆ The first function created by lambda should be labeled λ 1, the next one should be λ 2, and so on. a = [1, 2, 3]! b = [4, a, lambda: a[2][0]]! a[0] = b[1] is a! a[2] = b! c = b[:]! a[1] = c[2]() Global frame a

Login: 5 3. (5 points) Scanning We all know the higher order functions map, filter, and reduce. Today we re going to talk about their notquite-so-famous fourth sibling, scan. Scan is like reduce, only instead of accumulating the result into a single value, scan returns a list that contains all the intermediate values in reducing the list. Cross out lines from the implementation of the scan function below so that all doctests pass and the implementation contains as few lines of code as possible. You may want to look at the return statement first. Do not cross out any docstrings or doctests. def scan (f, lst, start ): """ Returns a list containing the intermediate values of reducing the list. >>> scan (add, [1, 2, 3, 4], 0) [1, 3, 6, 10] >>> scan (mul, [3, 2, 1, 0], 10) [30, 60, 60, 0] """ start = [] start = 0 accumulated = f( start ) accumulated = start def closure ( item ): nonlocal nonlocal accumulated start accumulated = f( item ) accumulated += f( item ) accumulated = f( accumulated, item ) accumulated += f( accumulated, item ) return accumulated return start + accumulated return item + accumulated return list ( map (f( lst ))) return list ( map (f, lst )) return list ( map ( closure ( lst ))) return list ( map ( closure, lst ))

6 4. (4 points) What would Python output Include all lines that the interpreter would display. If it would display a function, then write Function. If it would cause an error, write Error. Assume that you have started Python 3 and executed the following. These are entered into Python exactly as written. class SkipIterator : """ Iterates over a range starting from the beginning and skipping every nth element. """ def init (self, rng, n): self. obj = rng self. skip = n def iter ( self ): return self def next ( self ): result = self. obj. curr self. obj. curr += self. skip return result class SkippedNaturals : """ Iterable class for positive integers. """ def init ( self ): self. curr = 0 self. skip = 1 def iter ( self ): return SkipIterator ( self, self. skip ) Expression print("skipping Rope") p = SkippedNaturals () twos = iter (p) p. skip = p. skip + 1 threes = iter (p) next ( twos ) next(twos) next(threes) next(threes) Interactive Output Skipping Rope 0 1 2 4

Login: 7 5. (3 points) Interpretation Select which function(s) you would have to modify in order to add the new syntax features in Calculator. For full credit, you must justify your answers with at most two sentences. (a) (1 pt) = (equality checker) e.g. (= 3 1) returns False Justification: calc eval calc apply Both Neither No change to control flow. We just have to check for the operator now. (b) (1 pt) or e.g. (or (= 5 2) (= 2 2) (\ 1 0)) returns True Justification: calc eval calc apply Both Neither From discussion. Must change calc eval due to ors short-circuiting properties. (c) (1 pt) Creating and calling lambdas (Assume define has been implemented.) e.g. ( define square ( lambda (x) (* x x ))) ( square 4) Justification: calc eval calc apply Both Neither calc eval because lambda is a special form. Not to mention that you would also have to evaluate the operator now that the used can define it. calc apply because you need to create a new frame as a result of applying the user-defined function to the arguments once the function is called.. 6. (5 points) Waldo s Revenge Scheme Write wheres-waldo, a scheme procedure which takes in a scheme list and outputs the index of waldo if the symbol waldo exists in the list. Otherwise, it outputs the symbol nowhere. STk > ( wheres- waldo '( moe larry waldo curly )) 2 STk > ( wheres- waldo '(1 2)) nowhere ( define ( wheres- waldo lst ) ( cond (( null? lst ) ' nowhere ) (( equal? ( car lst ) 'waldo ) 0) ( else ( let (( found-him ( wheres-waldo ( cdr lst )))) (if ( equal? ' nowhere found-him ) ' nowhere (+ 1 found-him ) )) )))

8 7. (7 points) Generatree Here s an implementation of a Binary Search Tree class BST : def init (self, datum, left =None, right = None ): self. datum = datum self. left = left self. right = right (a) (1 pt) Draw A Tree Use the diagram below to reflect the tree generated by the following line: BST (10, BST (5, BST (1)), BST (42)) You may not need to use all of the circles. 10 5 42 1 X X X (b) (6 pt) 3.. 2.. 1 - Generate Paths! Now let s add a paths method to the BST class. It will return a generator that yields all of the paths from the root of the tree to a leaf. Each path is represented as a list containing the individual datums. def paths ( self ): """ Return a generator for all of the paths from the root to a leaf. >>> tree = BST (10, BST (5, BST (1)), BST (42)) >>> gen = tree. paths () >>> next ( gen ) [10, 5, 1] >>> for path in gen :... print ( path )... [10, 42] """ if self. left : for lp in self. left. paths (): yield [ self. datum ] + lp if self. right : for rp in self. right. paths (): yield [ self. datum ] + rp if not self. right and not self. left : yield [ self. datum ]

Login: 9 8. (5 points) Dealer always wins We want to play a card game and we must evenly deal out all of the cards to each player. We have a linked list (Link) of cards. In this case, cards are represented as numbers. deal deck returns a Python list of linked lists of cards for each player (reverse order of how the cards were dealt older cards on the bottom) and a linked list of the extra cards (in the original order). Do not call the Link constructor. def deal_ deck ( linked_ list, num_ of_ players ): """ Deals out a deck of cards. >>> deck = Link (1, Link (2, Link (3, Link (4, Link (5, Link (6, \ Link (7, Link (8, Link (9, Link (10)))))))))) >>> list_ of_ cards, remainder = deal_ deck ( deck, 4) >>> list_ of_ cards [ Link (5, Link (1)), Link (6, Link (2)), Link (7, Link (3)), Link (8, Link (4))] >>> remainder Link (9, Link (10)) """ # Create a list containing each player ' s hand. hands = [ Link. empty for i in range ( num_ of_ players )] # Give each player the right number of cards. for i in range ( len ( linked_list )// num_of_players ): # For each player for j in range ( num_ of_ players ): linked_ list, card = linked_ list. rest, linked_ list # Put the card in the player ' s hand card. rest = hands [j] hands [j] = card return hands, linked_ list 9. (3 points) (Extra Credit) Social Implications (a) (1 pt) Describe what software rot is. It s software rot (b) (2 pt) Modern cryptography methods are mathematically sound. Give two ways that an attacker could still steal information.