2020年4月6日月曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 12(Designing Algorithms)、Exercise 4、5の解答を求めてみる。

コード

#!/usr/bin/env python3
from unittest import TestCase, main
from typing import List, Tuple, Union

print('4, 5.')


class TestFindTwoSmallest(TestCase):
    def test_empty(self):
        self.assertEqual(find_two_smallest([]), ())

    def test_one(self):
        self.assertEqual(find_two_smallest([10]), (0,))

    def test_two(self):
        self.assertEqual(find_two_smallest([1, 1]), (0, 1))

    def test_two1(self):
        self.assertEqual(find_two_smallest([1, 2]), (0, 1))

    def test_five(self):
        self.assertEqual(find_two_smallest([5, 1, 4, 2, 3]), (1, 3))

    def test_five1(self):
        self.assertEqual(find_two_smallest([3, 2, 4, 1, 5]), (3, 1))

    def test_other(self):
        self.assertEqual(find_two_smallest([5, 1, 4, 1, 2, 3, 1]), (1, 3))


def find_two_smallest(nums: List[float]) -> Union[Tuple[int, int],
                                                  Tuple[int],
                                                  Tuple[()]]:
    if not nums:
        return ()
    if len(nums) == 1:
        return (0,)
    min1, min2 = nums[:2]
    min1_index = 0
    min2_index = 1
    if min1 > min2:
        min1, min2 = min2, min1
        min1_index, min2_index = min2_index, min1_index
    for i, num in enumerate(nums[2:], 2):
        if num < min1:
            min1, min2 = num, min1
            min1_index, min2_index = i, min1_index
        elif num < min2:
            min2 = num
            min2_index = i
    return min1_index, min2_index


if __name__ == "__main__":
    main()

入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))

% ./sample4.py -v
4, 5.
test_empty (__main__.TestFindTwoSmallest) ... ok
test_five (__main__.TestFindTwoSmallest) ... ok
test_five1 (__main__.TestFindTwoSmallest) ... ok
test_one (__main__.TestFindTwoSmallest) ... ok
test_other (__main__.TestFindTwoSmallest) ... ok
test_two (__main__.TestFindTwoSmallest) ... ok
test_two1 (__main__.TestFindTwoSmallest) ... ok

----------------------------------------------------------------------
Ran 7 tests in 0.000s

OK
%

0 コメント:

コメントを投稿