Exercises CME
Exercises CME
Introduction to Python
Exercises
Basics
CME 193
Introduction to Python
Exercises
Control flow
Disclaimer: Some of the following problems are inspired by problems from www.projecteuler.net. Have a
look if you are interested, there are some great challenges and Python is an excellent tool for solving them.
Exercise 2.1: Range
Type range(5) in the interpreter, what does the interpreter return? So what does for i in range(5)
mean?
Lets also find out whether the interpreter can help us understand the object range(5) better. Type
type(range(5)) in the interpreter. More on this soon!
Exercise 2.2: For loops
Use a for loop to:
(a) Print the numbers 0 to 100
Page 2
CME 193
Introduction to Python
Exercises
Functions
Page 3
CME 193
Introduction to Python
Exercises
(c) Explain the difference between the print and return keywords. What would change if instead of
print you would use return?
Exercise 3.2: Polynomial
Write a function that evaluates the polynomial 3x2 x + 2.
Exercise 3.3: Maximum
Write a function my_max(x,y) that returns the maximum of x and y. Do not use the max function, but
use if instead in following two ways:
(a) Use both if and else.
(b) Use if but not else (nor elif).
Exercise 3.4: Primes
(a) Write a function is_prime(n) that returns True only if n is prime.
(b) Note that apart from 2 and 3, all primes are of the form 6k 1 (though not all numbers of the
form 6k 1 are prime of course). Using this, we can improve the computation time by a factor 3.
Update your function to use this.
(c) Write a function that prints all primes up to n.
(d) Write a function that prints the first n primes.
Exercise 3.5: Root finding
Suppose f is a continuous function and f (a) < 0 and f (b) > 0 for some known a and b. For simplicity,
assume a < b. Then, there must exist some c such that f (c) = 0.
(a) Write a function root(f, a, b) that takes a function f and two floats a and b and returns the
root c. Hint: check the sign at the midpoint of the interval.
(b) Remove the assumption that a < b, and that f (a) < 0 and f (b) > 0, if your current code relies on
them.
(c) Add a check that prints
function evals have same sign
if f (a) > 0 and f (b) > 0 or if f (a) < 0 and f (b) < 0.
Lists
Page 4
CME 193
Introduction to Python
Exercises
Tuples
Page 5
CME 193
Introduction to Python
Exercises
a = b
b = a
so in some languages, you need to define a third variable like this
t = a
a = b
b = t
However, in Python you dont need to do this. How can you swap a and b in one line?
Exercise 5.2: Zip
Suppose we have two lists, x and y that give the x and y coordinates of a set of points. Create a list
with the coordinates (x,y) as a tuple. Hint: Find out about the zip function.
You have decided that actually, you need the two seperate lists, but unfortunately, you have thrown
them away. How can we use zip to unzip the list of tuples to get two lists again?
Exercise 5.3: Distances
Suppose we have two vectors, x and y, stored as tuples with n elements. Implement functions that
compute the l1 and l2 distances between x and y. Note that n is not explicitly given.
Dictionaries
Page 6
CME 193
Introduction to Python
Exercises
associated with some value. Write a function that takes a dictionary and a value, and returns the key
associated with this value.
What challenges do you face? How would you deal with those challenges?
File I/O
Numpy
Generate matrices A, with random Gaussian entries, B, a toeplitz matrix, where A Rnm and B Rmm ,
for n = 200, m = 500.
Exercise 8.1: Matrix operations
Calculate A + A, AA> , A> A and AB. Write a function that computes A(B I) for any .
Exercise 8.2: Solving a linear system
Generate a vector b with m entries and solve Bx = b.
Page 7
CME 193
Introduction to Python
Exercises
Scipy
10
Matplotlib
Page 8
CME 193
11
Introduction to Python
Exercises
Recursion
Page 9
CME 193
Introduction to Python
Exercises
12
Classes
(c) Add a method so that we can add two rational numbers with r1 + r2, here the __add__() method
is useful.
(d) Add a method to subtract two rational numbers. (__sub__)
(e) Add a method to multiply two rational numbers. (__mul__)
(f) Add a method to divide two rational numbers. (__div__)
(g) Add a method that compares whether two rational numbers are equal.
(h) Add a method to convert the rational number to a floating point (the __float__() method may
be handy).
(i) Add a method to print the rational number as p/q (the __str__() or __repr__ method is useful).
(j) Add any more functionality that you think is useful but I failed to mention.
Exercise 12.2: Binary search tree
In this exercise, we will implement a binary search tree. See http://en.wikipedia.org/wiki/Binary_
search_tree for an explanation.
(a) Define a class Node, and write the constructor, which takes one argument, value, and initializes
the left and right children to None.
(b) Write a function to print the tree.
(c) Write a function that inserts a new value in the tree at the right location.
(d) Write a function that looks up a value in the tree.
(e) Write a function that removes a value from the tree.
Page 10
CME 193
Introduction to Python
Exercises
See for example statsmodels ols or LinearRegression. While one can, and should, use written solvers,
its a good practice exercise.
(a) Setup an OLS class with fit and predict methods, to be coded later
(b) Write the fit method using numpys or scipys linear algebra module.
(c) Now write the predict function, that predicts yn given new Xn .
(d) Add a function that summarizes the model
(e) (Optional) Use Patsy and Pandas to support DataFrames and formulas, similar to R.
13
Iterators
14
Exception handling
Page 11
CME 193
15
Introduction to Python
Exercises
Unit testing
Page 12