Section 11.11. Exercises


11.11. Exercises

11-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.2 below. Write in "ERROR" if you think one will occur with the given input or "NONE" if there is no output.

11-2.

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

Table 11.2. Output Chart for Problem 11-1

Input

countToFour1

countToFour2

countToFour3

2

   

4

   

5

   

(nothing)

   


11-3.

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

  1. 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.

  2. 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. They can also take a set of arguments as input. Test your solutions for numbers and strings.

11-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.

11-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.

11-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 trivialthere is no need to implement the string operator functionality, but you do need to use the string format operator ( % ) explicitly.

11-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.) Then create another solution using the zip() built-in function.

11-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. Then convert it to using list comprehensions.

11-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.

11-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-11.

Functional Programming with map(). Write a program that takes a filename 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. Convert your solution to using list comprehensions.

11-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. (The general consensus is to use time.time() on POSIX and time.clock() on Win32 systems.) Note: The timeit() function is not related to the timeit module (introduced in Python 2.3).

11-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.

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

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

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

  4. 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.

11-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.

11-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.

11-16.

Upgrading easyMath.py. This script, presented as Example 11.1, served as the beginnings of a program to help young people develop their math skills. Further enhance this program by adding multiplication as a supported operation. Extra credit: Add division as well; this is more difficult as you must find valid integer divisors. Fortunately for you, there is already code to ensure the numerator is greater than the denominator so you do not need to support fractions.

11-17.

Definitions.

  1. Describe the differences between partial function application and currying.

  2. What are the differences between partial function application and closures?

  3. Finally, how do iterators and generators differ?

11-18.

*Synchronized Function Calling. Go back and review the husband and wife situation presented in Chapter 6 (Section 6.20) when introducing shallow and deep copies. They shared a common account where simultaneous access to their bank account might have adverse effects.

Create an application where calls to functions that change the account balance must be synchronized. In other words, only one process or thread can execute the function(s) at any given time. Your first attempt may use files, but a real solution will use decorators and synchronization primitives found in either the threading or mutex modules. You may look ahead to Chapter 17 for more inspiration.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net