開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
Head First はじめてのプログラミング ―頭とからだで覚えるPythonプログラミング入門 (Eric Freeman(著)、嶋田 健志(監修)、木下 哲也(翻訳)、株式会社オライリー・ジャパン)を8章(再帰と辞書 - 反復とインデックスを超えて)の頭の体操(370ページ)の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3
from unittest import TestCase, main
from typing import List
class MyTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test(self):
names = ['Kim', 'John', 'Josh']
ages = [28.0, 29.5, 27.0]
for name, age in zip(names, ages):
self.assertEqual(average_age(name), age)
users = {
'Kim': {
'age': 27,
'friends': ['John', 'Josh']
},
'John': {
'age': 24,
'friends': ['Kim', 'Josh'],
},
'Josh': {
'age': 32,
'friends': ['Kim']
},
}
def average_age(name: str) -> float:
friends: List[str] = users[name]['friends']
return sum([users[friend]['age'] for friend in friends]) / len(friends)
if __name__ == '__main__':
main()
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ ./sample3.py
E
======================================================================
ERROR: test (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./sample3.py", line 17, in test
self.assertEqual(average_age(name), age)
NameError: name 'average_age' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
$ ./sample3.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
$
0 コメント:
コメントを投稿