
CS 403/503 Exam 5 Fall 2009 Name __________________
Write each function below using Python. Be sure to use correct Python syntax.
CS 403 students: Your grade is based on your best 7 answers to these 9 problems.
CS 503 students: Your grade is based on your best 8 answers to these 9 problems.
1. cartesianProduct(A, B) returns the cartesian product of two sets A and B. For
example, cartesianProduct({1,2,3}, {'a','b'}) should return {(1,'a'), (1,'b'), (2,'a'),
(2,'b'), (3,'a'), (3,'b')}.
2. reduce(f, L, id) is equivalent to Haskell’s foldl and Smalltalk’s inject:into:. f is a
binary function, L is a list, and id is the value to return when L is empty. Do not
call the built-in reduce function.
3. scan(f, L) is similar to reduce. f is a binary function, and L is a list. When scan
returns, each position j of L should hold the result from applying function f to
the original elements at positions 0 through j of L. For example, if f(x, y) is a
function that returns x+y, and if L = [1,2,3,4,5], then scan(f, L) should modify
the contents of L so that L = [1,1+2,1+2+3,1+2+3+4,1+2+3+4+5] = [1,3,6,10,15].