2
1. (10 points) What Would Python Display
For each of the expressions in the table below, write the output displayed by the interactive Python interpreter
when the expression is evaluated. The output may have multiple lines. If an error occurs, write “Error”, but
include all output displayed before the error. If evaluation would run forever, write “Forever”. To display a
function value, write “Function”. The first two rows have been provided as examples.
The interactive interpreter displays the value of a successfully evaluated expression, unless it is None.
Assume that you have first started python3 and executed the statements on the left.
identity = lambda x: x
increment = lambda x: x + 1
def fif(c, t, f, x):
if c(x):
return t(x)
else:
return f(x)
def bounce(x, y):
while x < y:
if x <= (y and x):
print('a')
if x > 0:
print('b')
elif x > -5:
print('c')
x, y = -y, increment(x - y)
print(y)
crazy = lambda rich: 100 * rich
crazy = lambda rich: crazy(crazy(rich))
def ok(py):
def h(w):
print(py // 10)
return ok(py)
return lambda h: h(py)
Expression Interactive Output
pow(10, 2) 100
print(4, 5) + 1
4 5
Error
print(None, print(1, 2))
1 2
None None
fif(abs, print, print, -2) -2
bounce(1, 2)
a
b
0
a
c
-1
crazy(88) Error/Forever
ok(314)(identity) 314
2. (4 points) Implement factorial, which computes the factorial of a positive integer n. You may use any
of the functions defined above. You may not write if, else, and, or, or lambda in your solution.
def factorial(n):
"""The factorial of positive n: n * (n-1) * (n-2) * ... * 1
>>> factorial(4) # 4 * 3 * 2 * 1
24
>>> factorial(1)
1
"""
return n * fif(identity, factorial, increment, n-1)