X = [1, 2, 3) y = 4x + 3 a = 4 something ==== is wrong print a print Q x = 1 + 'abc' X = 1 / 0 import numpy as np np.add(1, 2, 3, 4) x = [1, 2, 3] print x[100] spam = "my all-time favorite" eggs = 1 / 0 print spam from math import sqrt def approx_pi(nterms=100): k = np.arange(nterms) return sqrt(12) * np.sum((-3.0) ** (-k) / (2.0 * k + 1.0)) print sqrt(12) print approx_pi(100) print approx_pi(1000) try: print "this block gets executed first" except: print "this block gets executed if there's an error" try: print "this block gets executed first" x = 1 / 0 # ZeroDivisionError print "we never get here" except: print "this block gets executed if there's an error" def safe_divide(a, b): try: return a / b except: print "oops, dividing by zero. Returning None." return None print safe_divide(15, 3) print safe_divide(1, 0) print safe_divide(15, 'three') def better_safe_divide(a, b): try: return a / b except ZeroDivisionError: print "oops, dividing by zero. Returning None." return None print better_safe_divide(15, 0) print better_safe_divide(15, 'three') def even_better_safe_divide(a, b): try: return a / b except ZeroDivisionError: print "oops, dividing by zero. Returning None." return None except TypeError: print "incompatible types. Returning None" return None print even_better_safe_divide(15, 3) print even_better_safe_divide(15, 0) print even_better_safe_divide(15, 'three') import os # the "os" module has useful operating system stuff def read_file(filename): if not os.path.exists(filename): raise ValueError("'{0}' does not exist".format(filename)) f = open(filename) result = f.read() f.close() return result %%file tmp.txt this is the contents of the file read_file('tmp.txt') read_file('file.which.does.not.exist') class NonExistentFile(RuntimeError): # you can customize exception behavior by defining class methods. # we won't discuss that here. pass def read_file(filename): if not os.path.exists(filename): raise NonExistentFile(filename) f = open(filename) result = f.read() f.close() return result print read_file('tmp.txt') print read_file('file.which.does.not.exist') try: print "doing something" except: print "this only happens if it fails" else: print "this only happens if it succeeds" try: raise ValueError() except: print "this only happens if it fails" else: print "this only happens if it succeeds" try: print "do something" except: print "this only happens if it fails" else: raise ValueError() try: print "do something" except: print "this only happens if it fails" else: print "this only happens if it succeeds" finally: print "this happens no matter what." try: raise ValueError() except: print "this only happens if it fails" else: print "this only happens if it succeeds" finally: print "this happens no matter what." try: print "do something" except: print "this only happens if it fails" else: print "this only happens if it succeeds" print "this happens no matter what." def divide(x, y): try: result = x / y except ZeroDivisionError: print "division by zero!" return None else: print "result is", result return result finally: print "some sort of cleanup" print divide(15, 3) print divide(15, 0) def read_all_from_file(filename): f = open(filename) contents = f.read() f.close() return contents def read_all_from_file(filename): # your code here read_all_from_file('tmp.txt') read_all_from_file('file.which.does.not.exist') read_all_from_file('file.which.does.not.exist', safe=True) def entropy(p): p = np.asarray(p) # convert p to array if necessary items = p * np.log(p) return -np.sum(items) p = np.arange(5.) p /= p.sum() print entropy(p) def entropy(p): p = np.asarray(p) # convert p to array if necessary print p items = p * np.log(p) print items return -np.sum(items) entropy(p) %%file test_script.py import numpy as np def entropy(p): p = np.asarray(p) # convert p to array if necessary items = p * np.log(p) import IPython; IPython.embed() return -np.sum(items) p = np.arange(5.) p /= p.sum() entropy(p) a = '123' b = '456' c = '789' total = a + b + c print total %%file pdb_test.py import pdb a = '123' pdb.set_trace() b = '456' c = '789' total = a + b + c print total %%file numbers.dat 123 456 789 %%file pdb_test2.py # File to experiment with Python debugger def add_lines(filename): f = open(filename) lines = f.read().split() f.close() result = lines[0] for line in lines[1:]: result += line return result filename = 'numbers.dat' total = add_lines(filename) print total %run -d pdb_test2.py """ A script to compare different root-finding algorithms. This version of the script is buggy and does not execute. It is your task to find an fix these bugs. The output of the script sould look like: Benching 1D root-finder optimizers from scipy.optimize: brenth: 604678 total function calls brentq: 594454 total function calls ridder: 778394 total function calls bisect: 2148380 total function calls """ from itertools import product import numpy as np from scipy import optimize FUNCTIONS = (np.tan, # Dilating map np.tanh, # Contracting map lambda x: x**3 + 1e-4*x, # Almost null gradient at the root lambda x: x+np.sin(2*x), # Non monotonous function lambda x: 1.1*x+np.sin(4*x), # Fonction with several local maxima ) OPTIMIZERS = (optimize.brenth, optimize.brentq, optimize.ridder, optimize.bisect) def apply_optimizer(optimizer, func, a, b): """ Return the number of function calls given an root-finding optimizer, a function and upper and lower bounds. """ return optimizer(func, a, b, full_output=True)[1].function_calls, def bench_optimizer(optimizer, param_grid): """ Find roots for all the functions, and upper and lower bounds given and return the total number of function calls. """ return sum(apply_optimizer(optimizer, func, a, b) for func, a, b in param_grid) def compare_optimizers(optimizers): """ Compare all the optimizers given on a grid of a few different functions all admitting a signle root in zero and a upper and lower bounds. """ random_a = -1.3 + np.random.random(size=100) random_b = .3 + np.random.random(size=100) param_grid = product(FUNCTIONS, random_a, random_b) print "Benching 1D root-finder optimizers from scipy.optimize:" for optimizer in OPTIMIZERS: print '% 20s: % 8i total function calls' % ( optimizer.__name__, bench_optimizer(optimizer, param_grid) ) if __name__ == '__main__': compare_optimizers(OPTIMIZERS)