## 2020年4月5日日曜日

### Python - Designing Algorithms - ファイルの読み込み、リスト内包表記、forループ、合計、平均

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:
for line in f:
if line.startswith('#'):
continue
total += int(line)
count += 1

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

if __name__ == "__main__":
main()
```

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

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

OK
%
```