实验目的

实验内容

provide default values for each argument and experiment with calling the function interactively. Try passing one, two, three, and four arguments. Then, try passing keyword arguments. Does the call adder(ugly=1, good=2) work? Why? Finally, generalize the new adder to accept and add an arbitrary number of keyword arguments, much like Exercise 3, but you'll need to iterate over a dictionary, not a tuple. (Hint: the dict.keys( ) method returns a list you can step through with afor or while.)

def f1(a, b): print a, b          # Normal args
def f2(a, *b): print a, b         # Positional varargs
def f3(a, **b): print a, b        # Keyword varargs
def f4(a, *b, **c): print a, b, c   # Mixed modes
def f5(a, b=2, c=3): print a, b, c # Defaults
def f6(a, b=2, *c): print a, b, c    # Defaults and positional varargs

Now, test the following calls interactively and try to explain each result. Do you think mixing matching modes is a good idea in general? Can you think of cases where it would be useful?

>>> f1(1, 2)
>>> f1(b=2, a=1)
>>> f2(1, 2, 3)
>>> f3(1, x=2, y=3)
>>> f4(1, 2, 3, x=2, y=3)
>>> f5(1)
>>> f5(1, 4)
>>> f6(1)
>>> f6(1, 3, 4)

思考题

Consider the following code, which uses a while loop and found flag to search a list of powers of 2, for the value of 2 raised to the 5th power (32). It's stored in a module file called power.py.

   1 L = [1, 2, 4, 8, 16, 32, 64]
   2 X=5
   3 found = i = 0
   4 while not found and i < len(L):
   5     if 2 ** X == L[i]:
   6         found = 1
   7     else:
   8         i = i+1
   9 if found:
  10     print 'at index', i
  11 else:
  12     print X, 'not found'

at index 5

As is, the example doesn't follow normal Python coding techniques. Follow the steps below to improve it. For all the transformations, you may type your code interactively or store it in a script file run from the system command line (using a file makes this exercise much easier).

  1. First, rewrite this code with a while loop else, to eliminate the found flag and final if statement.
  2. Next, rewrite the example to use a for loop with an else, to eliminate the explicit list indexing logic. Hint: to get the index of an item, use the list index method (L.index(X) returns the offset of the first X in list L).
  3. Next, remove the loop completely by rewriting the examples with a simple in operator membership expression.
  4. Finally, use a for loop and the list append method to generate the powers-of-2 list (L) instead of hard-coding a list literal.
  5. Deeper thoughts: (1) Do you think it would improve performance to move the 2**X expression outside the loops? How would you code that? (2) Python also includes a map(function, list) tool that can generate the powers-of-2 list too: map(lambda x: 2**x, range(7)). Try typing this code interactively.
ch3n2k.com | Copyright (c) 2004-2020 czk.