Practical Programming
An Introduction to Computer Science
Using Python 3
(Pragmatic Programmers)
(Pragmatic Bookshelf)
Paul Gries (著) Jennifer Campbell (著)
Jason Montojo (著) Lynn Beighley (編集)
開発環境
- OS X Yosemite - Apple (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python 3.4 (プログラミング言語)
Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 12(Designing Algorithms)、12.4(Exercises) 3-a, b.を解いてみる。
12.4(Exercises) 3-a, b.
コード(BBEdit)
sample3.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
def hopedaleAverage(filename):
i = 0
result = 0
with open(filename) as f:
f.readline()
line = f.readline()
for line in f:
if line.startswith('#'):
continue
line = line.strip()
result += int(line)
i += 1
return result / i
if __name__ == '__main__':
print(hopedaleAverage('hopedale.txt'))
入出力結果(Terminal, IPython)
$ cat hopedale.txt
Coloured fox fur production, HOPEDALE, Labrador, 1834-1842
#Source: C. Elton (1942) "Voles, Mice and Lemmings", Oxford Univ. Press
#Table 17, p.265--266
22
29
2
16
12
35
8
83
166
$ ./sample3.py
41.44444444444444
$
0 コメント:
コメントを投稿