開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART III.(Functions and Generators)、Test Your Knowledge: Part IV Exercises 、3.(varargs)を解いてみる。
その他参考書籍
3.(varargs)
コード(BBEdit)
sample.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- def adder(*args): if type(args[0]) == type(0) or type(args[0]) == type(1.0): sum = 0 else: sum = args[0][:0] for x in args: sum += x return sum for args in [(),('a',), ('a', 'b'), ('a', 'b', 'c'), (1,), (1, 2), (1, 2, 3), ([],), ([], [0]), ([1],), ([1], [2, 3]), ([1], [2, 3], [4, 5]), (1.2,), (1.2, 3.4), (1.2, 3.4, 5.6), ('a', 1), ({'a':1, 'b':2}, {'c':3, 'd':4})]: try: print('{0} sum: '.format(args), end='') print('{0}'.format(adder(*args))) except Exception as err: print(type(err), err, err.args)
入出力結果(Terminal)
$ ./sample.py () sum: <class 'IndexError'> tuple index out of range ('tuple index out of range',) ('a',) sum: a ('a', 'b') sum: ab ('a', 'b', 'c') sum: abc (1,) sum: 1 (1, 2) sum: 3 (1, 2, 3) sum: 6 ([],) sum: [] ([], [0]) sum: [0] ([1],) sum: [1] ([1], [2, 3]) sum: [1, 2, 3] ([1], [2, 3], [4, 5]) sum: [1, 2, 3, 4, 5] (1.2,) sum: 1.2 (1.2, 3.4) sum: 4.6 (1.2, 3.4, 5.6) sum: 10.2 ('a', 1) sum: <class 'TypeError'> Can't convert 'int' object to str implicitly ("Can't convert 'int' object to str implicitly",) ({'b': 2, 'a': 1}, {'c': 3, 'd': 4}) sum: <class 'TypeError'> unhashable type: 'slice' ("unhashable type: 'slice'",) $
0 コメント:
コメントを投稿