[PDF] [PDF] Midterm Exam 1 Solutions - EECS: www-insteecsberkeleyedu

Midterm Exam 1 Solutions own creation and the official 61A Midterm 1 Study Guide Assume that you have started Python 3 and executed the following 



Previous PDF Next PDF





[PDF] Midterm Exam 1A Answer key

Write a Python function inflation rate(initial, final) to compute and return the inflation rate given the initial and final values of a commodity Solution: def inflation_rate 



[PDF] Midterm Exam 1 Solutions - EECS: www-insteecsberkeleyedu

Midterm Exam 1 Solutions own creation and the official 61A Midterm 1 Study Guide Assume that you have started Python 3 and executed the following 



[PDF] solutions to the mid-term exam - Scott F Kaplan

Introduction to Computer Science I Spring 2014 Mid-term exam — Solutions 1 Question: Consider the following module of Python code def thing_one (x):



[PDF] CS100 Spring 2012 Midterm 1 Practice - NJIT

For questions 1-10, your answer to each question should be in three parts: i The answer you get to the question without consulting the Python interpreter ii The 



[PDF] Practice midterm exam - University of Washington

3 fév 2013 · Please write neatly; we cannot give credit for what we cannot read Good luck Page 2 Initials: Solutions 1 EXECUTE PYTHON EXPRESSIONS



[PDF] First Mid-Term Exam for CS101

9 fév 2015 · 4) What gets printed when Python execute that program? 1 a = 6 2 b = a/2 3 print b a 



[PDF] 01204111-midterm-60f - CPE, KU

find the value of f from these python expressions? C / 5 = (-32) / 01204111 Computer and Programming, Midterm Examination, 1° Semester/2017 EXAM SET 



[PDF] Strings in Python 1 Midterm#1 Exam Review - CS8 S17

21 avr 2017 · Strings in Python 1 Midterm#1 Exam Review CS 8: Introduction to Computer Science Lecture #6 Ziad Matni Dept of Computer Science, 



[PDF] Fall 2009 Midterm Exam 1 Solution (PDF) - MIT OpenCourseWare

run Idle or Python • talk, chat or email or otherwise converse with another person • use a music player Because of this midterm, we will not have software labs 



[PDF] CS 331 Summer 2017 Midterm Exam

9 Which of the following Python list methods has a worst-case runtime complexity of O(1)? (a) insert (b) 

[PDF] python mini projects with database

[PDF] python mit pdf

[PDF] python mysql connector

[PDF] python numpy partial differential equation

[PDF] python oop

[PDF] python oop exercises with solutions

[PDF] python oracle database programming examples pdf

[PDF] python oracle database programming pdf

[PDF] python pdfminer python3

[PDF] python physics examples

[PDF] python pour les nuls

[PDF] python private method

[PDF] python programming book in hindi pdf download

[PDF] python programming book pdf

[PDF] python programming examples pdf

CS 61A Structure and Interpretation of Computer Programs

Fall 2011Midterm Exam 1 SolutionsINSTRUCTIONS

You have 2 hours to complete the exam.

The exam is closed book, closed notes, closed computer, closed calculator, except a one-page crib sheet of your

own creation and the ocial 61A Midterm 1 Study Guide. Mark your answers ON THE EXAM ITSELF. If you are not sure of your answer you may wish to provide a

briefexplanation. All short answer sections can be successfully answered in a few sentences at most.Last Name

First Name

SID Login

TA & Section Time

Name of the person

to your leftName of the person to your rightAll the work on this exam is my own. (please sign)For sta use only

Q. 1Q. 2Q. 3Q. 4Total

/10/16/14/10/50 2

THIS PAGE INTENTIONALLY LEFT BLANK

Login:3

1. (10 p oints)Cal lExpressions Assume that you have started Python 3 and executed the following statements: from operator import add, mul def square(x): return mul(x, x) def curry(f): def g(x): return lambda y: f(x, y) return g

For each of the following call expressions, write the valueto which it evaluatesin the current environment

(which may dier from what is printed). If evaluating the call expression causes an error, write \error"and

the reason for the error. (a) (2 pt) add(4, square(print(2))) Error: print(2) evaluates to None. Cannot multiply None and None in the body of square. (b) (2 pt) add(4, square(square(2))) 20 (c) (2 pt) print(4, square(square(2))) None (d) (2 pt) curry(add)(square(2))(4) 8 (e) (2 pt) add(curry(square)(2), 4)

Error: Cannot add a function and an int.

4 2. (16 p oints)D eningF unctions (a) (5 pt) A functionstreakreturns the greatest number of 1's returned consecutively inncalls tocoin. Its second argumentcoinis a random, non-pure function that returns 1 sometimes and 0 other times. For instance,streakwould return 3, if 10 calls tocoinreturned these 10 values, in order:

0, 1, 1, 0, 1, 1, 1, 0, 0, 1

Your partner hands you the following implementation ofstreakmoments before this question is due. You

don't have time to rewrite it; you can only indent lines, dedent (un-indent) lines, and delete things. Mark

changes to the code below so that it correctly implementsstreak, using the following symbols: Place aright arrow(!) before a line to indent it by an additional 4 spaces. Place aleft arrow( ) before a line to dedent it by 4 spaces.

Circlea part of the code to delete it.6

4

2.(16point s)DefiningFunctions

(a)(5pt) Afu nctionstreakreturnsthegreatestnumb erof1"sretu rnedconsecutivelyi nncallstocoin. Itssecond argumentcoinisarand om, non-purefunctiont hatreturns1sometimesand 0othertimes. Forinst ance,streakwouldreturn3, if10callstocoinreturnedthese10values,inor der:

0,1,1, 0,1,1, 1,0,0, 1

Yourpartne rhandsyouthefollowing implementati onofstreakmomentsbeforethisqu estionisdue.You don"thavetim etorewriteit ;youcanonlyind entlin es,dedent(un-indent) lines,andd eletet hings. Mark changestothecodeb elows othatitcorr ectlyimpleme ntsstreak,us ingthefollowing symbols: •Placearightarrow(→)be forealinetoinde nti tbyanadditional 4spaces . •Placealeftarrow(←)be forealinetodede nti tby4spaces. •Circleapar tofthecode tod eleteit. defstreak(n,coin): """Returnthegreatest numberof 1"sreturnedconsecutively inncalls tocoin. coin--A functionthattakes zeroargumentsand returns0or 1. n--A positiveinteger n,k= 0,0,1 total=0 #consecutive1"s sincea 0 greatest=0 #Thegreatest numberofconsecutive 1"s whilek<= nandcoin() ==1: ifcoin== 0orcoin(n) ==0 orcoin()== 0: greatest,total= max(greatest,total), total,0 else: total=total +1 k=k+1 n=n+1 returnmax(greatest,total)

This circle

is optional

Login:5

(b) (5 pt) In Newton's method, the functioniterimprovemay cycle between two dierent guesses. For instance, consider nding the zero off(x) =x32x+ 2 (graphed below) using exact derivatives. A

starting guess of 1 updates to 0, which updates to 1 again. The cyclic pattern 1;0;1 is called a length-two

cycle, because it contains only two distinct elements before repeating.-2-1.5-1-0.500.511.52-0.80.81.62.43.24Write a new version ofiterimprovethat returnsFalseas soon as a length-two cycle of guesses occurs,

but otherwise behaves the same as the implementation from class (and printed on your study guide). def iter_improve(update, done, guess=1, max_updates=1000): k = 0 previous_guess = None while not done(guess) and k < max_updates: next_guess = update(guess) if previous_guess == next_guess: return False previous_guess, guess = guess, next_guess k = k + 1 return guess 6 (c) (4 pt) The gure below depicts an example piecewise function,f(x) =( x2x <1

3x x1-2-1.5-1-0.500.511.52-1123Dene a Python function calledpiecewisethat takes three arguments: two functionslowerfuncand

upperfunc, and a numbercutoff.lowerfuncandupperfunceach take a single number argument and return a single number value. piecewisereturns a new function that takes a single number argumentxand returnslowerfunc(x)if xis less thancutoff, orupperfunc(x)ifxis greater than or equal tocutoff. For example: >>> f = piecewise(lambda x: x*x, lambda x: 3-x, 1) >>> f(0.5) 0.25 >>> f(5) -2 def piecewise(lower_func, upper_func, cutoff): def f(x): if x < cutoff: return lower_func(x) else: return upper_func(x) return f (d) (2 pt) Assume that you have started Python 3 and executed the following statement: def self_apply(f): return f(f)

Write an expression in the blank operand position below, so that this call toselfapplyevaluates to 5:

self_apply( lambda f: 5 )

Login:7

3. (14 p oints)En vironments (a)

(6 pt) Fill in this environment diagram and expression tree that result from executing the Python code

in the lower right of the page. A complete answer will:

Complete all missing arrows.

Add all local frames created by applying user-dened functions.

Add all missing names and values.

Add all missing statements, expressions, and return values in the expression tree.Turtles Solution 5 from operator import mul def mutant(y): y, x = y+1, y+2 return ninja(y)/2 def ninja(x): return x + 2 def turtle(x): return mul(x, y) + 2 y, ninja = 5, turtle mutant(y) mutant(y)y, x = y+1, y+2 return ninja(y)/2 ninja(y) mutant(y): y, x = y+1, y+2 return ninja(y)/2 ninja(x): return x + 2 turtle(x) return mul(x, y) + 2 mutanty:6x:7 mutant:ninja:turtle:y:5 return mul(x, y) + 2turtlex:63216 8 (b)

(6 pt) Fill in this diagram of environments and values that result from executing the Python code in the

box below. Youdo notneed to draw an expression tree. A complete answer will:

Complete all missing arrows.

Add all local frames created by applying user-dened functions.

Add all missing names and values.Chuck Solution

4 x = 10 def walker(x): def texas(ranger): return x + 3 return texas def ranger(n): return x + walker(n)(n) texas = ranger ranger(2) ranger(n): return x + walker(n)(n) walker(x): def texas(ranger): return x + 3 return texas texas(ranger):

return x + 3texasranger:2(c)(2 pt) What is the value of the nested expressiontexas(ranger(2)), evaluated in the current environment

that results from executing the code in the previous problem? If evaluating this expression causes an error,

write \error" and the reason for the error. 28

Login:9

4. (10 p oints)D ataAbstraction

Anamountis a collection of nickels (5 cents) and pennies (1 cent), with the following behavior condition:

If an amountais constructed withnnickels andppennies, then 5nickels(a)+pennies(a)= 5n+p. Consider the following implementation of an abstract data type for amounts. def make_amount(n, p): return (n, p) def nickels(a): return a[0] def pennies(a): return a[1] (a)

(2 pt) Circle all abstraction barrier violations for this abstract data type in the following implementation

ofaddamounts, if there are any.Amount Solution 7

Login:9

4.(10point s)DataAbstraction

Anamountisacoll ect ionofnickels(5cents)andpen nie s(1cent),withthefollo wingbe haviorcondition: Ifanamoun taisconst ructedwithnnickelsandppennies,then5·nickels(a)+pennies(a)=5·n+p. Considerthefollowingim plementati onofanabstractdatatypeforamounts . defmake_amount(n,p): return(n,p) defnickels(a): returna[0] defpennies(a): returna[1]

(a)(2pt) Circleallabstractionb arrierv iolationsforthisabstractdataty peinthefollowingim plementation

ofaddamounts,if therear eany. defadd_amounts(a1,a2): n1=nickels(a1) n2=nickels(a2) n=n1 +n2 p=a1[1] +a2[1] return(n,p) (b)(4pt) Anamou ntisminimali fithasn omorethan4pennies.R edefine thecons truct orsothat all amountsareminimal, butthe behaviorconditionofthety pestillhol ds.

defmake_amount(n,p): (b)(4 pt) An amount is minimal if it has no more than 4 pennies. Redene the constructor so that all

amounts are minimal, but the behavior condition of the type still holds. def make_amount(n, p): return (n + p // 5, p % 5) 10 (c) (4 pt) Suppose we redenemakeamountfunctionally, as follows: def make_amount(n, p): def dispatch(message): if message == 0: return n elif message == 1: return p return dispatch

Redene the selectors to implement a valid abstract data type for amounts using this constructor, in which

all amounts are minimal. That is,penniesshould never return a number greater than 4. def nickels(a): return a(0) + a(1) // 5 def pennies(a): return a(1) % 5quotesdbs_dbs14.pdfusesText_20