LoginSignup
0
0

More than 1 year has passed since last update.

【競プロ】Python3 標準入出力の簡略化

Last updated at Posted at 2023-05-22

はじめに

競技プログラミングでは標準入出力を使うことがあり、コーディングで毎回int(input())だのlist(map(int,input().split()))とタイプするのが非常に面倒です。
タイプミスで閉じカッコが足りなかったり余計だったりしたまま実行してしまう、というポカミスも多いので、いっそ関数化した方が(個人的には)楽かなと思ったので作成しました。

リスト

コーディング中に関数名を忘れやすいので(ぉぃ)、最後にまとめて三重引用符コメントとして記述しています。
解答コードはこの下から書き始めると良いでしょう。
数値を扱う問題のみ考慮に入れました。文字列を扱う問題はまたの機会に。

コード
# coding: utf-8
def int_input():
    return int(input())


def multi_int_input():
    return map(int, input().strip().split())


def line_to_int_list():
    return list(map(int, input().strip().split()))


def input_to_n_lists(n: int):
    result = []
    for _ in range(n):
        result.append(line_to_int_list())
    return result


def join_list_to_str(l: list):
    return " ".join(list(map(str, l)))


"""
int_input()             数値を一つ入力
multi_int_input()       数値を複数入力
line_to_int_list()      一行のスペース区切りデータを一次元リストに格納
input_to_n_lists(n)     n行のスペース区切りデータを多次元リストに格納
join_list_to_str(l)     一次元数値リストlをスペース区切り文字列に変換
"""

動作確認

入力コードと出力コード
n = int_input()
x, y, z = multi_int_input()
a = line_to_int_list()
m = int_input()
q = input_to_n_lists(m)

print(n)
print(x,y,z)
print(a)
print(join_list_to_str(a))
print(m)
print(q)
標準入力
6
23 4 89
34 8 29 3 23 57 1 44 28 40
5
0 2
1
2
0 5
0 29
1
2
実行結果 - 標準出力
6
23 4 89
[34, 8, 29, 3, 23, 57, 1, 44, 28, 40]
34 8 29 3 23 57 1 44 28 40
5
[[0, 2], [1], [2], [0, 5], [0, 29]]

おわりに

今回のコードはpaizaやAtCoderの問題を意識しました。解答アルゴリズムの考案はともかく、データ受け渡し方法を考えすぎてタイムロスするのはキツイですね…

他の競技プログラミングサイトのPython解答コードでは、異なる仕様を見かけます。

  • LeetCode
    • クラス化されている、メソッド名・引数があらかじめ決まっている
  • HackerRank
    • 標準入力部分はコード化済み、出力もリスト形式のままで良い(スペース区切り文字列にしなくて良い)
    • if __name__=='__main__':で始まる点は最初面食らった

ともあれ、まずはアルゴリズムの勉強ですね、はい。
いやその前に===を間違えたり、for文やwhile文、if文の:を忘れたりするのがまずいな(爆

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0