12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3. varargs. Two alternative adder functions are shown in the following file, adders.py.The hard part here is figuring out how to initialize an accumulator to an emptyvalue of whatever type is passed in. The first solution uses manual type testing tolook for an integer, and an empty slice of the first argument (assumed to be asequence) if the argument is determined not to be an integer. The second solutionuses the first argument to initialize and scan items 2 and beyond, much likeone of the min function variants shown in Chapter 16.The second solution is better. Both of these assume all arguments are of thesame type, and neither works on dictionaries (as we saw in Part II, + doesn’twork on mixed types or dictionaries). You could add a type test and special codeto allow dictionaries, too, but that’s extra credit:def adder1(*args):print 'adder1',if type(args[0]) == type(0):sum = 0else:sum = args[0][:0]for arg in args:sum = sum + argreturn sum# Integer?# Init to zero# else sequence:# Use empty slice of arg1def adder2(*args):print 'adder2',sum = args[0]for next in args[1:]:sum += nextreturn sum# Init to arg1# Add items 2..Nfor func in (adder1, adder2):print func(2, 3, 4)print func('spam', 'eggs', 'toast')print func(['a', 'b'], ['c', 'd'], ['e', 'f'])% python adders.pyadder1 9adder1 spameggstoastadder1 ['a', 'b', 'c', 'd', 'e', 'f']adder2 9adder2 spameggstoastadder2 ['a', 'b', 'c', 'd', 'e', 'f']4. Keywords. Here is my solution to the first part of this exercise (file mod.py). Toiterate over keyword arguments, use the **args form in the function header, anduse a loop (e.g., for x in args.keys( ): use args[x]), or use args.values( ) tomake this the same as summing *args positionals:def adder(good=1, bad=2, ugly=3):return good + bad + uglyPart IV, Functions | 657

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!