開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
初めてのコンピュータサイエンス(Jennifer Campbell、Paul Gries、Jason Montojo、Greg Wilson(著)長尾 高弘(翻訳))の9章(集合と辞書)、9.5(練習問題)、7.を解いてみる。
9.5(練習問題)、7.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 def fetchAndSet1(d, key, new_value): if key in d: temp = d[key] d[key] = new_value return temp raise KeyError('Unable to replace value for nonexistent key') def fetchAndSet2(d, key, new_value): if d.get(key, False): temp = d[key] d[key] = new_value return temp raise KeyError('Unable to replace value for nonexistent key') print('inを使用') d = {'a':1,'b':2} print(d) fetchAndSet1(d, 'a', 3) print(d) try: fetchAndSet1(d, 'c', 4) print(d) except KeyError as e: print(type(e), e, e.args) except Exception as e: print(type(e), e, e.args) fetchAndSet1(d, 'b', 5) print(d) print('getを使用') d = {'a':1,'b':2} print(d) fetchAndSet2(d, 'a', 3) print(d) try: fetchAndSet2(d, 'c', 4) print(d) except KeyError as e: print(type(e), e, e.args) except Exception as e: print(type(e), e, e.args) fetchAndSet1(d, 'b', 5) print(d)
入出力結果(Terminal)
$ ./sample.py inを使用 {'a': 1, 'b': 2} {'a': 3, 'b': 2} <class 'KeyError'> 'Unable to replace value for nonexistent key' ('Unable to replace value for nonexistent key',) {'a': 3, 'b': 5} getを使用 {'a': 1, 'b': 2} {'a': 3, 'b': 2} <class 'KeyError'> 'Unable to replace value for nonexistent key' ('Unable to replace value for nonexistent key',) {'a': 3, 'b': 5} $
0 コメント:
コメントを投稿