LoginSignup
2
3

More than 3 years have passed since last update.

Pythonで競技プログラミングする際の入力チートシート

Last updated at Posted at 2019-11-12

はじめに

Pythonで競技プログラミングを始めたので、入力部分の実装時間を短縮するための入力のテンプレートを作成しました。自分用の備忘録のようなものです。

環境

Python 3.5.x(AtCoderで動作したのを確認)

本編

基本となる入力用のクラス


class Scan():

    def intarr(self):
        line = input()
        array = line.split(' ')
        num_array = [int(n) for n in array]
        return num_array

    def strarr(self):
        line = input()
        return line.split(' ')

入力する行数が決まっている場合(整数)

def main():
    sc = Scan()
    n = sc.intarr()
    print(n)

# 入力例
10 4 0
# 出力
[10, 4, 0]

入力する行数が決まっていない場合(整数)

def main():
    sc = Scan()
    array = []
    while True:
        try:
            array.append(sc.intarr())
        except ValueError:
            break

    print(array)

# 入力例
3 5 7
1 2 3 4 5
2 3
#出力
[[3, 5, 7], [1, 2, 3, 4, 5], [2, 3]]

文字列

def main():
    sc = Scan()
    n = sc.strarr()
    print(n)

# 入力例
Hello World
# 出力
['Hello', 'World']

終わりに

こうした方が実行速度が早いなどのアドバイスがありましたらお願いします。

2
3
3

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
2
3