Pythonで標準入力を取得する時のテクニック
先日のCodeforcesに参加した際に他の方のコーディングで参考になったテクニックです。
下のような感じで標準入力された値を計算して標準出力するような問題があるとします。
# input : # A B # C D 1 2 3 4 # output # A+D B+C 5 5
そういった時に私の頭にすぐ浮かんだコードは以下な感じ。
# input input = raw_input() A,B = input.split() input = raw_input() C,D = input.split() a = int(A) b = int(B) c = int(C) d = int(D) # output print a+d,b+c
入力に関する処理だけで8行も使っており冗長すぎます。
そして、他の人のコードを見て感動した方法が以下です。
# input a,b = map(int, raw_input().split()) c,d = map(int, raw_input().split()) # output print a+b, c+d
なんと、入力がたったの2行で済むんですね。
次回からはこれでスピードアップ予定です(`・ω・´)