2020年4月5日日曜日

開発環境

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

コード

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

print('3-a, b.')


class TestHopedaleAverage(TestCase):
    def setUp(self):
        self.filename = 'hopedale.txt'

    def test_loop(self):
        self.assertAlmostEqual(
            hopedale_average_loop(self.filename),
            41.4444444)

    def test_list_comprehension(self):
        self.assertAlmostEqual(
            hopedale_average_list_comprehension(self.filename),
            41.4444444)


def hopedale_average_loop(filename: str) -> float:
    total = 0
    count = 0
    with open(filename) as f:
        _ = f.readline()
        for line in f:
            if line.startswith('#'):
                continue
            total += int(line)
            count += 1
    return total / count


def hopedale_average_list_comprehension(filename: str) -> float:
    with open(filename) as f:
        _ = f.readline()
        nums = [int(line) for line in f if not line.startswith('#')]
    return sum(nums) / len(nums)


if __name__ == "__main__":
    main()

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

% ./sample3.py -v
3-a, b.
test_list_comprehension (__main__.TestHopedaleAverage) ... ok
test_loop (__main__.TestHopedaleAverage) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
%

0 コメント:

コメントを投稿