近頃Scalaの勉強を時間を見つけてやってます。
Scalaスケーラブルプログラミング[コンセプト&コーディング] (Programming in Scala)
- 作者: Martin Odersky,Lex Spoon、Bill Venners,羽生田栄一,長尾高弘
- 出版社/メーカー: インプレスジャパン
- 発売日: 2009/08/21
- メディア: 単行本
- 購入: 17人 クリック: 600回
- この商品を含むブログ (120件) を見る
とりあえず3章まで読み終わった。
何となく3章の内容をpythonで書き直してみた。
with,三項演算子、reduceを初めて使って見たけどかなりソースがきれいにかけますね。
from __future__ import with_statement import sys lines=[] with file(sys.argv[0], 'r') as fp: for line in fp: lines.append(line) longest_line = reduce(lambda x,y:len(x)>len(y) and x or y,lines) max_width=len(str(len(longest_line))) for line in lines: num_spaces = max_width - len(str(len(line))) padding = " " * num_spaces sys.stdout.write(padding + str(len(line))+ " | " + line)
【結果】
38 | from __future__ import with_statement 11 | import sys 1 | 9 | lines=[] 1 | 35 | with file(sys.argv[0], 'r') as fp: 20 | for line in fp: 27 | lines.append(line) 1 | 65 | longest_line = reduce(lambda x,y:len(x)>len(y) and x or y,lines) 38 | max_width=len(str(len(longest_line))) 1 | 19 | for line in lines: 49 | num_spaces = max_width - len(str(len(line))) 31 | padding = " " * num_spaces 61 | sys.stdout.write(padding + str(len(line))+ " | " + line)