開発環境
- Mac OS X Snow Leopard (OS)
- WingIDE
- Script言語: Python
『初めてのコンピュータサイエンス』(Jennifer Campbell, Paul Gries, Jason Montojo, Greg Wilson 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-463-7)の9章(集合と辞書), 9.5(練習問題), 13を解いてみる。
13.
コード
import sys # Count all the birds. def count_birds(): count = {} for filename in sys.argv[1:]: infile = open(filename, 'r') for line in infile: name = line.strip() count[name] = count.get(name, 0) + 1 infile.close() return count # Invert the dictionary. def invert_dic(d): freq = {} for (name, times) in d.items(): if times in freq: freq[times].append(name) else: freq[times] = [name] return freq # Print. def print_dic(d): for key in sorted(d): print key for name in d[key]: print ' ', name print_dic(invert_dic(count_birds()))
入出力結果(Python Shell)
問題のコードのそれぞれを関数にして、それを合成関数にしただけだけど、これでいいのかな~最後の1行の合成関数を見れば、何をしてるかは少しはわかりやすくなった気がするけど。とりあえずPython ShellでEvaluatingできたからコード自体には問題ないと思うので次に進むことに!
0 コメント:
コメントを投稿