開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
初めてのコンピュータサイエンス(Jennifer Campbell、Paul Gries、Jason Montojo、Greg Wilson(著)長尾 高弘(翻訳))の12章(各種ツール)の12.7(練習問題)13~18を解いてみる。
13.
Noneと値は比較できない。なので、最大値と最小値の初期化には引数のリストの要素を使うように修正。(引数が空のリストの場合には最大値、最小値をNoneにする。)
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def find_min_max(values): print(values) if not values: print("リストは空っぽ") else: min = max = values[0] for value in values[1:]: if value < min: min = value elif value > max: max = value print("最小値は{0}です。".format(min)) print("最大値は{0}です。".format(max)) if __name__ == '__main__': find_min_max([]) find_min_max([5]) find_min_max([5,5]) find_min_max([1,2]) find_min_max([2, 1]) find_min_max([1,2,10, 3,4]) find_min_max([2,3,1,4,5]) find_min_max([1,0,2,9,3,8,4,7,5,6])
入出力結果(Terminal)
$ ./sample.py [] リストは空っぽ [5] 最小値は5です。 最大値は5です。 [5, 5] 最小値は5です。 最大値は5です。 [1, 2] 最小値は1です。 最大値は2です。 [2, 1] 最小値は1です。 最大値は2です。 [1, 2, 10, 3, 4] 最小値は1です。 最大値は10です。 [2, 3, 1, 4, 5] 最小値は1です。 最大値は5です。 [1, 0, 2, 9, 3, 8, 4, 7, 5, 6] 最小値は0です。 最大値は9です。 $
14.
0未満の時(負の数)のとき関数が失敗する。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def summation(limit): total = 0 current = limit if limit < 0: while current != 0: total += current current += 1 else: while current != 0: total += current current -= 1 return total if __name__ == '__main__': print(summation(-10)) print(summation(10)) print(summation(0))
入出力結果(Terminal)
$ ./sample.py -55 55 0 $
15.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def compute_reciprocals(values): reciprocals = [] for value in values: try: reciprocals.append(1 / value) except Exception as err: print(type(err), err, err.args) reciprocals.append(None) return reciprocals if __name__ == '__main__': for values in [[1,2,3,4,5], [1,0,2,3,4,5,0]]: print(compute_reciprocals(values))
入出力結果(Terminal)
$ ./sample.py [1.0, 0.5, 0.3333333333333333, 0.25, 0.2] <class 'ZeroDivisionError'> division by zero ('division by zero',) <class 'ZeroDivisionError'> division by zero ('division by zero',) [1.0, None, 0.5, 0.3333333333333333, 0.25, 0.2, None] $
16.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- # stringという文字列を含む行の中で一番下の行番号とその行の内容を要素とする # リストを返す関数 def find_last(filename, string): line_number = 0 # ステッパ(カウンタかも?) last = [None, None] # 最良ホルダ with open(filename) as f: # f 固定値 for line in f: # line ステッパ line_number += 1 if string in line: last = [line_number, line] return last import math def standard_deviation(values): # 標準偏差値を求める sum = 0.0 # ギャザラ for value in values: # value ステッパ sum += value average = sum / len(values) std_deviation = 0.0 # ギャザラ for value in values: # value ステッパ std_deviation += (value - average) ** 2 deviation_average = std_deviation / len(values) # 一時変数 return math.sqrt(deviation_average) if __name__ == '__main__': filename = "sample.py" print(find_last(filename, "def")) print(find_last(filename, "return")) print(standard_deviation([1,2,3,4,5])) print(standard_deviation([0,0,5,5,5]))
入出力結果(Terminal)
$ ./sample.py [31, ' print(find_last(filename, "def"))\n'] [32, ' print(find_last(filename, "return"))\n'] 1.4142135623730951 2.449489742783178 $
17.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def mean(values): sum = 0 for value in values: if type(value) != type(10) and type(value) != type(1.0): raise ValueError("リストに数値以外の要素が含まれている") sum += value return sum / len(values) def median(values): sorted_l = sorted(values) l = len(sorted_l) if l % 2 == 0: return (sorted_l[l // 2 - 1] + sorted_l[l // 2 ]) / 2 else: return sorted_l[l // 2 + 1] def mode(values): res = [] count = {} for value in values: if value in count: count[value] += 1 else: count[value] = 1 m = max(count.values()) for k, v in count.items(): if v == m: res.append(k) return res if __name__ == '__main__': for values in ([1,2,3,4,5], [1,2,3,4,5,1,2,3,4,1,2,3,1,2,1,0]): for func in (mean, median, mode): print(values, func.__name__, func(values)) try: mean([1,'a']) except Exception as err: print(type(err), err, err.args)
入出力結果(Terminal)
$ ./sample.py [1, 2, 3, 4, 5] mean 3.0 [1, 2, 3, 4, 5] median 4 [1, 2, 3, 4, 5] mode [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 1, 2, 1, 0] mean 2.1875 [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 1, 2, 1, 0] median 2.0 [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 1, 2, 1, 0] mode [1] <class 'ValueError'> リストに数値以外の要素が含まれている ('リストに数値以外の要素が含まれている',) $
18.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def process_file(filename): with open(filename) as f: for line in f: line = line.strip() print(line)
0 コメント:
コメントを投稿