Unlicensed-7-PDF187-188_Haltermanpythonbook

advertisement
8.8.
178
EXERCISES
(d) Which of the functions sum1, sum2, and sum3 produce a side effect? What is the side effect?
(e) Which function may not use the val variable?
(f) What is the scope of the variable val? What is its lifetime?
(g) What is the scope of the variable i? What is its lifetime?
(h) Which of the functions sum1, sum2, and sum3 demonstrate good functional independence?
Why?
2. Consider the following Python code:
def next_int1():
cnt = 0
cnt += 1
return cnt
global_count = 0
def next_int2():
global_count += 1
return global_count
def main():
for i = range(0, 5):
print(next_int1(), next_int2())
main()
(a) What does the program print?
(b) Which of the functions next_int1 and next_int2 is the best function for the intended purpose? Why?
(c) What is a better name for the function named next_int1?
(d) The next_int2 function works in this context, but why is it not a good implementation of
function that always returns the next largest integer?
3. What does the following Python program print?
def sum(m=0, n=0, r=0):
return m + n + r
def main():
print(max())
print(max(4))
print(max(4, 5))
print(max(5, 4))
print(max(1, 2, 3))
print(max(2.6, 1.0, 3))
main()
4. Consider the following function:
©2011 Richard L. Halterman
Draft date: November 13, 2011
8.8.
179
EXERCISES
def proc(n):
if n < 1:
return 1
else:
return proc(n/2) + proc(n - 1)
Evaluate each of the following expressions:
(a) proc(0)
(b) proc(1)
(c) proc(2)
(d) proc(3)
(e) proc(5)
(f) proc(10)
5. Rewrite the gcd function so that it implements Euclid's method but uses iteration instead of recursion.
6. Classify the following functions as pure or impure. x is a global variable.
(a)
def f1(m, n):
return 2 *m + 3 *n
(b)
def f2(n)
return n - 2
(c)
def f3(n):
return n - x
(d)
def f4(n):
print(2 *n)
(e)
def f5(n):
m = eval(input())
return m
* n
(f)
def f6(n):
m = 2 *n
p = 2 *m - 5
return p - n
©2011 Richard L. Halterman
Draft date: November 13, 2011
Download