開発環境
- macOS Catalina - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.8 (プログラミング言語)
Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 12(Designing Algorithms)、Exercise 2の解答を求めてみる。
コード
#!/usr/bin/env python3
from unittest import TestCase, main
from typing import List, Tuple
print('2-a, b, c.')
class TestMinIndex(TestCase):
def test_1(self):
self.assertEqual(min_find([1]), (1, 0))
def test_2(self):
self.assertEqual(min_find([1, 1]), (1, 0))
def test_3(self):
self.assertEqual(min_find([2, 4, 6, 8, 1, 3, 5, 7]), (1, 4))
class TestMaxIndex(TestCase):
def test_1(self):
self.assertEqual(max_find([1]), (1, 0))
def test_2(self):
self.assertEqual(max_find([1, 1]), (1, 0))
def test_3(self):
self.assertEqual(max_find([2, 4, 6, 8, 1, 3, 5, 7]), (8, 3))
class TestMinOrMaxIndex(TestCase):
def test_1(self):
self.assertEqual(min_find([1]), (1, 0))
def test_2(self):
self.assertEqual(min_find([1, 1]), (1, 0))
def test_3(self):
self.assertEqual(min_find([2, 4, 6, 8, 1, 3, 5, 7]), (1, 4))
def test_max1(self):
self.assertEqual(min_or_max_index([1], False), (1, 0))
def test_max2(self):
self.assertEqual(min_or_max_index([1, 1], False), (1, 0))
def test_max3(self):
self.assertEqual(min_or_max_index([2, 4, 6, 8, 1, 3, 5, 7], False),
(8, 3))
# b.
def min_find(nums: List[int]) -> Tuple[int, int]:
# a. for loop
minimum_value = nums[0]
index = 0
for i, num in enumerate(nums[1:], 1):
if num < minimum_value:
minimum_value = num
index = i
return minimum_value, index
# c.
def max_find(nums: List[int]) -> Tuple[int, int]:
maximum_value = nums[0]
index = 0
for i, num in enumerate(nums[1:], 1):
if num > maximum_value:
maximum_value = num
index = i
return maximum_value, index
def min_or_max_index(nums: List[int], is_min=True) -> Tuple[int, int]:
if is_min:
return min_find(nums)
return max_find(nums)
if __name__ == "__main__":
main()
入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))
% ./sample2.py -v
2-a, b, c.
test_1 (__main__.TestMaxIndex) ... ok
test_2 (__main__.TestMaxIndex) ... ok
test_3 (__main__.TestMaxIndex) ... ok
test_1 (__main__.TestMinIndex) ... ok
test_2 (__main__.TestMinIndex) ... ok
test_3 (__main__.TestMinIndex) ... ok
test_1 (__main__.TestMinOrMaxIndex) ... ok
test_2 (__main__.TestMinOrMaxIndex) ... ok
test_3 (__main__.TestMinOrMaxIndex) ... ok
test_max1 (__main__.TestMinOrMaxIndex) ... ok
test_max2 (__main__.TestMinOrMaxIndex) ... ok
test_max3 (__main__.TestMinOrMaxIndex) ... ok
----------------------------------------------------------------------
Ran 12 tests in 0.001s
OK
%
0 コメント:
コメントを投稿