52
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

競技プログラミングを Python 3 で解く

Last updated at Posted at 2018-05-11

はじめに

Python 大好きおじさんなので競プロも Python で解きたいです.
Python 触り始めて少ししか経っていないので訂正等ありましたらご指摘ください.

#チートシート

標準入力

1行から入力

文字

>> ABC
input.py
S = input()
print(S) # ABC
>> ABC
input.py
S = list(input())
print(S) # ['A', 'B', 'C']
>> A B C
input.py
S = input().split()
print(S) # ['A', 'B', 'C']

数字

>> 1
input.py
N = int(input())
print(N) # 1
>> 1 2 3
input.py
A, B, C = map(int, input().split())
print(A) # 1
>> 1 2 3
input.py
L = [int(i) for i in input().split()]
print(L) # [1, 2, 3]
>> 1 2 3 (上と同じ)
input.py
L = list(map(int, input().split()))
print(L) # [1, 2, 3]

複数行から入力

文字

1次元
input.txt
3
ABC
DEF
GHI
input.py
N = int(input())
S = [input() for _ in range(N)]
print(S) # ['ABC', 'DEF', 'GHI']
2次元
input.txt
3 3
ABC
DEF
GHI
input.py
H, W = map(int, input().split())
S = []
for _ in range(H):
    S.append(list(input()))
print(S) # [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
input.txt
3 3
A B C
D E F
G H I
input.py
H, W = map(int, input().split())
A = [input().split() for _ in range(H)]
print(A) # [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]

数字

1次元
input.txt
3
123
456
789
input.py
N = int(input())
A = [int(input()) for _ in range(N)]
print(A) # [123, 456, 789]
2次元
input.txt
3 3
1 2 3
4 5 6
7 8 9
input.py
H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
print(A) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

その他の関数

素数判定

prime_judge.py
def prime_judge(p):
    p = abs(p)
    if p == 2:
        return True
    if p < 2 or p & 1 == 0:
        return False
    return pow(2, p-1, p) == 1

素数判定をします.
素数なら True, 素数でないなら False を返します.

http://d.hatena.ne.jp/pashango_p/20090704/1246692091

更新

新しいフレーズに出会ったら随時更新していきます.
2018/05/11 16:40 文字の2次元配列の入力コードを変更しました.

52
41
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
52
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?