12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

print adder( )print adder(5)print adder(5, 6)print adder(5, 6, 7)print adder(ugly=7, good=6, bad=5)% python mod.py6101418185. (and 6.) Here are my solutions to exercises 5 and 6 (file dicts.py). These arejust coding exercises, though, because <strong>Python</strong> 1.5 added the dictionary methodsD.copy( ) and D1.update(D2) to handle things like copying and adding(merging) dictionaries. (See <strong>Python</strong>’s library manual or O’Reilly’s <strong>Python</strong>Pocket Reference for more details.) X[:] doesn’t work for dictionaries, as they’renot sequences (see Chapter 8 for details). Also, remember that if you assign (e =d)rather than copying, you generate a reference to a shared dictionary object;changing d changes e, too:def copyDict(old):new = {}for key in old.keys( ):new[key] = old[key]return newdef addDict(d1, d2):new = {}for key in d1.keys( ):new[key] = d1[key]for key in d2.keys( ):new[key] = d2[key]return new% python>>> from dicts import *>>> d = {1: 1, 2: 2}>>> e = copyDict(d)>>> d[2] = '?'>>> d{1: 1, 2: '?'}>>> e{1: 1, 2: 2}>>> x = {1: 1}>>> y = {2: 2}>>> z = addDict(x, y)>>> z{1: 1, 2: 2}658 | Appendix B: Solutions to End-of-Part Exercises

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

Saved successfully!

Ooh no, something went wrong!