開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Python 3.6 (プログラミング言語)
行列プログラマー(Philip N. Klein (著)、 松田 晃一 (翻訳)、 弓林 司 (翻訳)、 脇本 佑紀 (翻訳)、 中田 洋 (翻訳)、 齋藤 大吾 (翻訳)、オライリージャパン)の1章(体)、1.7(問題)、Python の内包表記に関する問題、問題1.7.1、1.7.2、1.7.3を取り組んでみる。
問題1.7.1、1.7.2、1.7.3
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 1.7.1
def my_filter(l, num):
return [n for n in l if n % num != 0]
# 1.7.2
def my_lists(l):
return [list(range(1, x + 1)) for x in l]
# 1.7.3
def my_function_composition(f, g):
return {x: g[f[x]] for x in f}
import unittest
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_my_filter(self):
self.assertEqual(my_filter([1, 2, 4, 5, 7], 2), [1, 5, 7])
def test_my_lists1(self):
self.assertEqual(my_lists([1, 2, 4]), [[1], [1, 2], [1, 2, 3, 4]])
def test_my_lists2(self):
self.assertEqual(my_lists([0]), [[]])
def test_my_function_composition(self):
f = {0: 'a', 1: 'b'}
g = dict(a='apple', b='banana')
self.assertEqual(my_function_composition(
f, g), {0: 'apple', 1: 'banana'})
if __name__ == '__main__':
unittest.main()
入出力結果(Terminal, IPython)
$ ./sample7_1.py -v test_my_filter (__main__.Test) ... ok test_my_function_composition (__main__.Test) ... ok test_my_lists1 (__main__.Test) ... ok test_my_lists2 (__main__.Test) ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.000s OK $
0 コメント:
コメントを投稿