DOC PREVIEW
Berkeley COMPSCI 61A - Lecture 25

This preview shows page 1-2-3-4-5 out of 16 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

61A Lecture 25Friday, October 28Friday, October 28, 2011From Last Time: Adjoining to a Tree Set2531 791187911878Right! Left! Right!None None8NoneStop!87879118531 79118Friday, October 28, 2011From the Exam: Pruned Trees3a b c dTrue True False(a,b) (a,c) (a,d)prunedFriday, October 28, 2011From the Exam: Pruned Trees4pruned(a, c)pruned(a.right, c.right)a cimplieswhat about c.left?NoneNoneNone NoneFriday, October 28, 2011From the Exam: Pruned Trees5pruned(a, d)pruned(a.left, d.left)awould implydNoneNoneNone Not NoneFriday, October 28, 2011From the Exam: Pruned Trees6def pruned(t1, t2): if t2 is None: return True if t1 is None: return False return pruned(t1.left, t2.left) and pruned(t1.right, t2.right)a b c dRecursive call: both branches are pruned as wellBase cases: one (or more) of the trees is NoneFriday, October 28, 2011Today's Topic: Handling ErrorsSometimes, computers don't do exactly what we expect•A function receives unexpected argument types•Some resource (such as a file) does not exist•Network connections are lost7Grace Hopper's Notebook, 1947, Moth found in a Mark II ComputerFriday, October 28, 2011Different Error Handling Policies8VersusFriday, October 28, 2011ExceptionsA built-in mechanism in a programming language to declare and respond to exceptional conditionsPython raises an exception whenever an error occursExceptions can be handled by the program, preventing a crashUnhandled exceptions will cause Python to halt execution9Exceptions are objects! They have classes with constructors.They enable non-local continuations of control:If f calls g and g calls h, exceptions can shift control from h to f without waiting for g to return.However, exception handling tends to be slow.Mastering exceptions:Friday, October 28, 2011Assert StatementsAssert statements raise an exception of type AssertionError10assert <expression>, <string>Assertions are designed to be used liberally and then disabled in "production" systems. "O" stands for optimized.python3 -OWhether assertions are enabled is governed by a bool __debug__DemoFriday, October 28, 2011Raise StatementsExceptions are raised with a raise statement.11raise <expression><expression> must evaluate to an exception instance or class.Exceptions are constructed like any other object; they are just instances of classes that inherit from BaseException.TypeError -- A function was passed the wrong number/type of argumentNameError -- A name wasn't foundKeyError -- A key wasn't found in a dictionaryRuntimeError -- Catch-all for troubles during interpretationFriday, October 28, 2011Try StatementsTry statements handle exceptions12try: <try suite>except <exception class> as <name>: <except suite>...Execution rule:The <try suite> is executed first;If, during the course of executing the <try suite>, an exception is raised that is not handled otherwise, andIf the class of the exception inherits from <exception class>, thenThe <except suite> is executed, with <name> bound to the exceptionFriday, October 28, 2011Handling ExceptionsException handling can prevent a program from terminating13>>> try: x = 1/0 except ZeroDivisionError as e: print('handling a', type(e)) x = 0handling a <class 'ZeroDivisionError'>>>> x0Multiple try statements: Control jumps to the except suite of the most recent try statement that handles that type of exception.DemoFriday, October 28, 2011WWPD: What Would Python Do?How will the Python interpreter respond?14 >>> invert_safe(1/0) >>> try: invert_safe(0) except ZeroDivisionError as e: print('Handled!') >>> inverrrrt_safe(1/0)def invert(x): result = 1/x # Raises a ZeroDivisionError if x is 0 print('Never printed if x is 0') return resultdef invert_safe(x): try: return invert(x) except ZeroDivisionError as e: return str(e)Friday, October 28, 2011Example: Safe Iterative ImprovementIterative improvement is a higher-order function•The update argument provides better guesses•The done argument indicates completion•Used to implement Newton's method (find_root)15newton.py Page 2 3.0 """ def update(guess): return cube_root_update(guess, x) def done(guess): return guess * guess * guess == x return iter_improve(update, done)def square_root_newton(x): """Return the square root of x. >>> square_root_newton(9) 3.0 """ return find_root(lambda y: y * y é x) def cube_root_newton(x): """Return the cube root of x. >>> cube_root_newton(27) 3.0 """ return find_root(lambda y: y * y * y é x) def approx_derivative(f, x, delta=1eé5): """Return an approximation to the derivative of f at x.""" df = f(x + delta) é f(x) return df/deltadef newton_update(f): """Return an update function for f using Newton's method.""" def update(x): return x é f(x) / approx_derivative(f, x) return updatedef find_root(f, guess=1): """Return a guess of a zero of the function f, near guess. >>> from math import sin >>> find_root(lambda y: sin(y), 3) 3.141592653589793 """ return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)@maindef run(): interact()newton.py Page 2 3.0 """ def update(guess): return cube_root_update(guess, x) def done(guess): return guess * guess * guess == x return iter_improve(update, done)def square_root_newton(x): """Return the square root of x. >>> square_root_newton(9) 3.0 """ return find_root(lambda y: y * y é x) def cube_root_newton(x): """Return the cube root of x. >>> cube_root_newton(27) 3.0 """ return find_root(lambda y: y * y * y é x) def approx_derivative(f, x, delta=1eé5): """Return an approximation to the derivative of f at x.""" df = f(x + delta) é f(x) return df/deltadef newton_update(f): """Return an update function for f using Newton's method.""" def update(x): return x é f(x) / approx_derivative(f, x) return updatedef find_root(f, guess=1): """Return a guess of a zero of the function f, near guess. >>> from math import sin >>> find_root(lambda y: sin(y), 3) 3.141592653589793 """ return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)@maindef run(): interact()Friday, October 28, 2011Exception ChainingThe except suite of a try statement can raise another


View Full Document

Berkeley COMPSCI 61A - Lecture 25

Documents in this Course
Lecture 1

Lecture 1

68 pages

Midterm

Midterm

5 pages

Midterm

Midterm

6 pages

Lecture 35

Lecture 35

250 pages

Lecture 14

Lecture 14

125 pages

Lecture 2

Lecture 2

159 pages

Lecture 6

Lecture 6

113 pages

Lecture 3

Lecture 3

162 pages

Homework

Homework

25 pages

Lecture 13

Lecture 13

117 pages

Lecture 29

Lecture 29

104 pages

Lecture 11

Lecture 11

173 pages

Lecture 7

Lecture 7

104 pages

Midterm

Midterm

6 pages

Midterm

Midterm

6 pages

Lecture 8

Lecture 8

108 pages

Lab 4

Lab 4

4 pages

Lecture 7

Lecture 7

52 pages

Lecture 20

Lecture 20

129 pages

Lecture 15

Lecture 15

132 pages

Lecture 9

Lecture 9

95 pages

Lecture 30

Lecture 30

108 pages

Lecture 17

Lecture 17

106 pages

Load more
Download Lecture 25
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 25 and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 25 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?