< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204174051007164253053075245

Exercises

1:

Arguments. Compare the following three functions:

								
def countToFour1():
    for eachNum in range(5):
        print eachNum,

def countToFour2(n):
    for eachNum in range(n, 5):
        print eachNum,

def countToFour3(n=1):
    for eachNum in range(n, 5):
        print eachNum,

							

What do you think will happen as far as output from the program, given the following input values? Enter the output into Table 11.1 below. Write in "ERROR" if you think one will occur with the given input or " NONE" if there is no output.

Table 11.2. Output chart for Problem 11-1
Input countToFour1 countToFour2 countToFour3
2      
4      
5      
(nothing)      

2:

Functions. Combine your solutions for Exercise 5-2. such that you create a combination function which takes the same pair of numbers and returns both their sum and product at the same time.

3:

Functions. In this exercise, we will be implementing the max() and min() built-in functions.

(a) Write simple functions max2() and min2() that take two items and return the larger and smaller item, respectively. They should work on arbitrary Python objects. For example, max2(4, 8) and min2(4, 8) would each return 8 and 4, respectively.

(b) Create new functions my_max() and my_min() that use your solutions in part (a) to recreate max() and min(). These functions return the largest and smallest item of non-empty sequences, respectively. Test your solutions for numbers and strings.

4:

Return values. Create a complementary function to your solution for Exercise 5-13. Create a function that takes a total time in minutes and returns the equivalent in hours and minutes.

5:

Default arguments. Update the sales tax script you created in Exercise 5-7 such that a sales tax rate is no longer required as input to the function. Create a default argument using your local tax rate if one is not passed in on invocation.

6:

Variable-length arguments. Write a function called printf(). There is one positional argument, a format string. The rest are variable arguments that need to be displayed to standard output based on the values in the format string, which allows the special string format operator directives such as %d, %f, etc. HINT: the solution is trivial—there is no need to implement the string operator functionality, but you do need to use the string format operator ( % ) explicitly.

7:

Functional programming with map(). Given a pair of identically-sized lists, say [1, 2, 3,], and ['abc', 'def', 'ghi',], merge both lists into a single list consisting of tuples of elements of each list so that our result looks like: {[(1, 'abc'), (2, 'def'), (3, 'ghi'),}. (Although this problem is similar in nature to a problem in Chapter 6, there is no direct correlation between their solutions.)

8:

Functional programming with filter(). Use the code you created for Exercise 5-4 to determine leap years. Update your code so that it is a function if you have not done so already. Then write some code to take a list of years and return a list of only leap years.

9:

Functional programming with reduce(). Review the code in Section 11.7.2 that illustrated how to sum up a set of numbers using reduce(). Modify it to create a new function called average() that calculates the simple average of a set of numbers.

10:

Functional programming with filter(). In the Unix file system, there are always two special files in each folder/directory: '.' indicates the current directory and '..' represents the parent directory. Given this knowledge, take a look at the documentation for the os.listdir() function and describe what this code snippet does:

								
files = filter(lambda x: x and x[0] != '.', os.listdir(folder))

							
11:

Functional programming with map(). Write a program that takes a file name and "cleans" the file by removing all leading and trailing whitespace from each line. Read in the original file and write out a new one, either creating a new file or overwriting the existing one. Give your user the option to pick which of the two to perform.

12:

Passing functions. Write a sister function to the testit() function described in this chapter. Rather than testing execution for errors, timeit() will take a function object (along with any arguments), and time how long it takes to execute the function. Return the following values: function return value, time elapsed. You can use time.clock() or time.time(), whichever provides you with greater accuracy.

13:

Functional programming with reduce() and Recursion. In Chapter 8, we looked at N factorial or N! as the product of all numbers from 1 to N.

(a)Take a minute to write a small, simple function called mult(x, y) that takes x and y and returns their product.

(b) Use the mult() function you created in part (a)along with reduce() to calculate factorials.

(c) Discard the use of mult() completely and use a lambda expression instead.

(d) In this chapter, we presented a recursive solution to finding N! Use the timeit() function you completed in the problem above and time all three versions of your factorial function (iterative, reduce(), and recursive). Explain any differences in performance, anticipated and actual.

14:

*Recursion. We also looked at Fibonacci numbers in Chapter 8. Rewrite your previous solution for calculating Fibonacci numbers (Exercise 8-9) so that it now uses recursion.

15:

*Recursion. Rewrite your solution to Exercise 6-5 which prints a string backwards to use recursion. Use recursion to print a string forward and backward.


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.