888
875

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 1 year has passed since last update.

AtCoderで始めるPython入門

888
Last updated at Posted at 2019-04-04

はじめに

AtCoder では AtCoder Beginner Contest(ABC)が開催されており、ABC-A問題 は Python の実装方法を知っていれば解ける問題が多くあります。ABC-A問題を解けるようになるために、本記事では実装方法を整理しました。

本記事について

本記事について説明します。

目的

本記事の目的は下記です。

Python で ABC-A問題 を概ね解けるようになる。

注意事項

本記事の注意事項は下記の通りです。ご理解の程をよろしくお願い致します。

  • 本記事は個人で作成した記事であり、AtCoder株式会社は作成に関与していません。
  • ABC-A問題をすべて解けるようになる記事ではありません。
  • 一部のマイナーバージョンで本記事とは異なる仕様があります。
  • 体系的な Python を学習する記事ではありません。

構成

各章は下記の構成です。

章 章名 内容
第1章 入出力処理 入出力処理を学べる
第2章 演算 演算を学べる
第3章 代入文 代入文を学べる
第4章 制御構文 制御構文を学べる
第5章 組み込み型 組み込み型を学べる
第6章 組み込み関数 組み込み関数を学べる
第7章 関数定義 関数定義を学べる
- 付録 Python の学習を深める情報を学べる

各節項は下記の構成です。

項目 内容
サンプルコード 問題から得られた知見と検証によって得られた知見を整理したコード
入力 サンプルコードの入力例
実行結果 サンプルコードの実行結果
解答例 AtCoder で AC になったコード

バージョン / 言語

サンプルコードは Python の下記バージョンで動作することを確認しました。

Python 3.11.4

解答例は AtCoder の下記言語で AC になることを確認しました。

Python (CPython 3.11.4)

コーディングスタイル

本記事のコードは pycodestyle の下記バージョンでコーディングスタイルを確認しました。

pycodestyle 2.14.0

コードリポジトリ

本記事のコードは下記のリポジトリで公開しています。

参考

本記事は下記を参考にしました。

最後に

サービスを提供しているAtCoder株式会社と、交流している競技プログラマの方々に感謝を致します。

第1章 入出力処理

第1章では入出力処理について説明します。

1.1 出力

キーポイント

  • 標準出力はprint関数で出力する。
  • 数値の出力はprint(数値)で出力する。
  • 変数の出力はprint(変数)で出力する。
  • 文字列の出力はprint("文字列")で出力する。
  • 文字列の出力/定義は文字列をダブルクォーテーション"、またはシングルクォーテーション'で囲う。
  • print関数の区切り文字はprint(出力データ, sep="区切り文字")で指定する。
  • print関数の区切り文字を指定しない場合print(出力データ)、区切り文字は 半角スペース となる。
  • print関数の末尾文字はprint(出力データ, end="末尾文字")で指定する。
  • print関数の末尾文字を指定しない場合print(出力データ)、末尾文字は 改行 となる。

整数(int)

  • 整数を出力する

整数を出力する場合、print(整数)で出力する。

サンプルコード:sample_1-1-1.py
print(10)
実行結果
10
  • 整数を変数に格納して出力する

整数を変数に格納して出力する場合、変数 = 整数で変数を定義し、print(変数)で出力する。

サンプルコード:sample_1-1-2.py
x = 20
print(x)
実行結果
20

浮動小数点数(float)

  • 浮動小数点数を出力する

浮動小数点数を出力する場合、print(浮動小数点数)で出力する。

サンプルコード:sample_1-1-3.py
print(2.9)
実行結果
2.9
  • 浮動小数点数を変数に格納して出力する

浮動小数点数を変数に格納して出力する場合、変数 = 浮動小数点数で変数を定義し、print(変数)で出力する。

サンプルコード:sample_1-1-4.py
x = 3.5
print(x)
実行結果
3.5

文字列(str)

文字列の出力/定義は文字列をダブルクォーテーション"、またはシングルクォーテーション'で囲う。

  • 文字列を出力する

文字列を出力する場合、print("文字列") または print('文字列') で出力する。

サンプルコード:sample_1-1-5.py
print("Hello World!")
実行結果
Hello World!
  • 文字列を変数に格納して出力する

文字列を変数に格納して出力する場合、変数 = "文字列"で変数を定義し、print(変数)で出力する。

サンプルコード:sample_1-1-6.py
x = "Hello World!"
print(x)
実行結果
Hello World!
  • 文字列を変数に格納し、変数のインデックスを指定して文字を出力する

文字列を変数に格納し、変数のインデックスを指定して文字を出力する場合、print(変数[インデックス])で出力する。

サンプルコード:sample_1-1-7.py
x = "Hello World!"
print(x[0])
実行結果
H
サンプルコード:sample_1-1-8.py
x = "Hello World!"
print(x[11])
実行結果
!

リスト(list)

  • 1次元リストを出力する

1次元リストを出力する場合、print(リスト)で出力する。

サンプルコード:sample_1-1-9.py
x = [1, 2, 3, 4, 5]
print(x)
実行結果
[1, 2, 3, 4, 5]
  • 1次元リストの各要素を出力する

1次元リストの各要素を出力する場合、for 変数 in リスト:でループ処理し、print(変数)で出力する。

サンプルコード:sample_1-1-10.py
x = [1, 2, 3, 4, 5]
for i in x:
    print(i)
実行結果
1
2
3
4
5
  • 1次元リストのインデックス指定して各要素を出力する

1次元リストのインデックス指定して各要素を出力する場合、for 変数 in range(リストの長さ):でループ処理し、print(リスト[変数])で出力する。

サンプルコード:sample_1-1-11.py
x = [1, 2, 3, 4, 5]
for i in range(5):
    print(x[i])
実行結果
1
2
3
4
5
  • 2次元リストを出力する

2次元リストを出力する場合、print(リスト)で出力する。

サンプルコード:sample_1-1-12.py
x = [[1, 2, 3], [4, 5, 6]]
print(x)
実行結果
[[1, 2, 3], [4, 5, 6]]
  • 2次元リストの各行を出力する

2次元リストの各行を出力する場合、for 1次元リスト in 2次元リスト:でループ処理し、print(1次元リスト)で出力する。

サンプルコード:sample_1-1-13.py
x = [[1, 2, 3], [4, 5, 6]]
for rows in x:
    print(rows)
実行結果
[1, 2, 3]
[4, 5, 6]
  • 2次元リストの各要素を出力する

2次元リストの各要素を出力する場合、for 1次元リスト in 2次元リスト:でループ処理し、さらにfor 変数 in 1次元リスト:でネストし、print(変数)で出力する。

サンプルコード:sample_1-1-14.py
x = [[1, 2, 3], [4, 5, 6]]
for rows in x:
    for columns in rows:
        print(columns)
実行結果
1
2
3
4
5
6
  • 2次元リストの各要素をインデックス指定して出力する

2次元リストの各要素をインデックス指定して出力する場合、for 変数A in range(2次元リストの長さ):でループ処理し、さらにfor 変数B in range(1次元リストの長さ):でネストし、print(リスト[変数A][変数B])で出力する。

サンプルコード:sample_1-1-15.py
x = [[1, 2, 3], [4, 5, 6]]
for i in range(2):
    for j in range(3):
        print(x[i][j])
実行結果
1
2
3
4
5
6

区切り文字の指定

print関数の区切り文字はprint(出力データ, sep="区切り文字")で指定する。

  • 区切り文字を指定しない

区切り文字を指定しない場合print(出力データ)、区切り文字が 半角スペース で出力される。

サンプルコード:sample_1-1-16.py
x = 1
y = 2
z = 3
print(x, y, z)
実行結果
1 2 3
  • カンマを指定する

カンマ,を指定する場合、print(出力データ, sep=",")で出力する。

サンプルコード:sample_1-1-17.py
x = 1
y = 2
z = 3
print(x, y, z, sep=",")
実行結果
1,2,3
  • 区切り文字なしを指定する

区切り文字なしを指定する場合、print(出力データ, sep="")で出力する。

サンプルコード:sample_1-1-18.py
x = 1
y = 2
z = 3
print(x, y, z, sep="")
実行結果
123
  • 改行を指定する

改行\nを指定する場合、print(出力データ, sep="\n")で出力する。

サンプルコード:sample_1-1-19.py
x = 1
y = 2
z = 3
print(x, y, z, sep="\n")
実行結果
1
2
3

末尾文字の指定

print関数の末尾文字はprint(出力データ, end="末尾文字")で指定する。

  • 末尾文字を指定しない

末尾文字を指定しない場合print(出力データ)、末尾文字が 改行\nで出力される。

サンプルコード:sample_1-1-20.py
print("x")
print("y")
print("z")
実行結果
x
y
z
  • 末尾文字なしを指定する

末尾文字なしを指定する場合、print(出力データ, end="")で出力する。

サンプルコード:sample_1-1-21.py
print("x", end="")
print("y", end="")
print("z", end="")
実行結果
xyz
  • 半角スペースを指定する

半角スペース を指定する場合、print(出力データ, end=" ")で出力する。

サンプルコード:sample_1-1-22.py
print("x", end=" ")
print("y", end=" ")
print("z", end=" ")
実行結果
x y z

アンパック

  • アンパックを利用して文字を出力する

アンパック*を利用して、文字列から各文字を半角スペース で区切り、出力することができる。出力する場合、print(*文字列)で出力する。

サンプルコード:sample_1-1-23.py
x = "ABC"
print(*x)
実行結果
A B C

ABC329 A - Spread | 提出結果

解答例:answer_1-1-1.py
S = input()
print(*S)
  • アンパックを利用して1次元リストの要素を出力する

アンパック*を利用して、1次元リストの要素を出力することができる。出力する場合、print(*リスト)で出力する。要素は半角スペース で区切られる。

サンプルコード:sample_1-1-24.py
x = [1, 2, 3, 4, 5]
print(*x)
実行結果
1 2 3 4 5
  • アンパックの区切り文字としてカンマを指定する

アンパックの区切り文字としてカンマ,を指定する場合、print(*出力データ, sep=",")で出力する。

サンプルコード:sample_1-1-25.py
x = "ABC"
print(*x, sep=",")
実行結果
A,B,C
サンプルコード:sample_1-1-26.py
x = [1, 2, 3, 4, 5]
print(*x, sep=",")
実行結果
1,2,3,4,5
  • アンパックの区切り文字として改行を指定する

アンパックの区切り文字として改行\nを指定する場合、print(*出力データ, sep="\n")で出力する。

サンプルコード:sample_1-1-27.py
x = "ABC"
print(*x, sep="\n")
実行結果
A
B
C
サンプルコード:sample_1-1-28.py
x = [1, 2, 3, 4, 5]
print(*x, sep="\n")
実行結果
1
2
3
4
5

1.2 コメントアウト

キーポイント

  • 処理を実行しない場合やコメントを入れる場合などはコメントアウトを使用する。
  • 1行のコメントアウトは#(シャープ1つ)を使用する。
  • 複数行のコメントアウトは"""(ダブルクォーテーション3つ)または'''(シングルクォーテーション3つ)を使用する。

1行

1行のコメントアウトは#(シャープ1つ)を使用する。#より後ろの処理は実行されなくなる。

サンプルコード:sample_1-2-1.py
print(10)
# print(20)
# print(30)
print(40)  # 行の途中からでもコメントアウトを使用できる。
実行結果
10
40

複数行

複数行のコメントアウトは"""(ダブルクォーテーション3つ)または'''(シングルクォーテーション3つ)を使用する。コメントアウトする処理を"""または'''で囲む。囲まれた処理は実行されなくなる。

サンプルコード:sample_1-2-2.py
print(10)
"""
print(20)
print(30)
print(40)
"""
print(50)
実行結果
10
50

1.3 入力

キーポイント

  • 標準入力はinput関数で入力する(文字列(str)型で入力される)。
  • 標準入力から整数を得たい場合、整数(int)型int(input())に変換する。
  • 標準入力から浮動小数点数を得たい場合、浮動小数点数(float)型float(input())に変換する。
  • 標準入力から得た文字列を区切りたい場合、split関数を用いてinput().split("区切り文字")と使用する。
  • split関数で区切り文字を指定しない場合input().split()、半角スペース で区切られる。
  • 複数列の整数の標準入力を複数の変数に格納する場合、map関数を用いてmap(int, input().split())と使用する。
  • 複数列の整数の標準入力をリストに格納する場合、map関数を用いてlist(map(int, input().split()))と使用する。
  • 複数行の整数の標準入力をリストに格納する場合、リスト内包表記で[int(input()) for 変数 in range(入力行数)]と使用する。

1行 / 1列

  • 整数を変数に格納する

整数を変数に格納する場合、変数 = int(input())で格納する。

入力
10
サンプルコード:sample_1-3-1.py
x = int(input())
print(x)
実行結果
10
  • 文字列を1つの変数に格納する

文字列を1つの変数に格納する場合、変数 = input()で格納する。

入力
Hello world!
サンプルコード:sample_1-3-2.py
x = input()
print(x)
実行結果
Hello world!
  • 文字列を複数の変数に格納する

文字列を複数の変数に格納する場合、変数A, 変数B, 変数C = input()で格納する。

入力
123
サンプルコード:sample_1-3-3.py
x, y, z = input()  # 123を整数(int)型ではなく、文字列(str)型で変数に格納する
print(x, y, z)
実行結果
1 2 3
入力
abc
サンプルコード:sample_1-3-4.py
x, y, z = input()
print(x, y, z)
実行結果
a b c

1行 / 複数列

  • 整数を複数の変数に格納する

整数を複数の変数に格納する場合、変数A, 変数B = map(int, input().split())で格納する。

入力
1 2
サンプルコード:sample_1-3-5.py
x, y = map(int, input().split())
print(x)
print(y)
実行結果
1
2

ABC012 A - スワップ | 提出結果

解答例:answer_1-3-1.py
A, B = map(int, input().split())
print(B, A)

ABC161 A - ABC Swap | 提出結果

解答例:answer_1-3-2.py
X, Y, Z = map(int, input().split())
print(Z, X, Y)
  • 文字列を複数の変数に格納する

文字列を複数の変数に格納する場合、変数A, 変数B = input().split()で格納する。

入力
Hello world!
サンプルコード:sample_1-3-6.py
x, y = input().split()
print(x)
print(y)
実行結果
Hello
world!

ABC012 A - スワップ | 提出結果

解答例:answer_1-3-3.py
A, B = input().split()
print(B, A)

ABC161 A - ABC Swap | 提出結果

解答例:answer_1-3-4.py
X, Y, Z = input().split()
print(Z, X, Y)

ABC051 A - Haiku | 提出結果

解答例:answer_1-3-5.py
s1, s2, s3 = input().split(",")
print(s1, s2, s3)

ABC325 A - Takahashi san | 提出結果

解答例:answer_1-3-6.py
S, T = input().split()
print(S, "san")
  • 整数をリストに格納する

整数をリストに格納する場合、リスト = list(map(int, input().split()))で格納する。

入力
1 2 3 4 5
サンプルコード:sample_1-3-7.py
x = list(map(int, input().split()))
print(x)
実行結果
[1, 2, 3, 4, 5]
  • 文字列をリストに格納する

文字列をリストに格納する場合、リスト = input().split()で格納する。

入力
Hello world !
サンプルコード:sample_1-3-8.py
x = input().split()
print(x)
実行結果
['Hello', 'world', '!']

複数行 / 1列

  • 整数を複数の変数に格納する

整数を複数の変数に格納する場合、変数 = int(input())を複数行で格納する。

入力
1
2
サンプルコード:sample_1-3-9.py
x = int(input())
y = int(input())
print(x, y)
実行結果
1 2

整数を複数の変数に格納する場合、変数A, 変数B = [int(input()) for 変数 in range(変数の数)]で格納する。

入力
1
2
サンプルコード:sample_1-3-10.py
x, y = [int(input()) for i in range(2)]
print(x, y)
実行結果
1 2
  • 整数をリストに格納する

整数をリストに格納する場合、リスト = [int(input()) for 変数 in range(変数の数)]で格納する。

入力
1
2
3
サンプルコード:sample_1-3-11.py
x = [int(input()) for i in range(3)]
print(x)
実行結果
[1, 2, 3]
  • 入力行数が指定され、整数をリストに格納する

入力行数(N = 3)が指定され、整数をリストに格納する場合、変数 = int(input())で入力行数を格納し、リスト = [int(input()) for 変数 in range(変数)]でリストに格納する。

入力
3
1
2
3
サンプルコード:sample_1-3-12.py
N = int(input())
x = [int(input()) for i in range(N)]
print(x)
実行結果
[1, 2, 3]
  • 文字列をリストに格納する

文字列をリストに格納する場合、リスト = [input() for 変数 in range(変数の数)]で格納する。

入力
a
b
c
サンプルコード:sample_1-3-13.py
x = [input() for i in range(3)]
print(x)
実行結果
['a', 'b', 'c']
  • 入力行数が指定され、文字列をリストに格納する

入力行数(N = 3)が指定され、文字列をリストに格納する場合、変数 = int(input())で入力行数を格納し、リスト = [input() for 変数 in range(変数)]でリストに格納する。

入力
3
a
b
c
サンプルコード:sample_1-3-14.py
N = int(input())
x = [input() for i in range(N)]
print(x)
実行結果
['a', 'b', 'c']

複数行 / 複数列

  • 整数をリストに格納する

整数をリストに格納する場合、リスト = [list(map(int, input().split())) for 変数 in range(入力行数)]となる。

入力
1 2 3
4 5 6
7 8 9
サンプルコード:sample_1-3-15.py
x = [list(map(int, input().split())) for i in range(3)]
print(x)
実行結果
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • 入力行数が指定され、整数をリストに格納する

入力行数(N = 3)が指定され、整数をリストに格納する場合、変数 = int(input())で入力行数を格納し、リスト = [list(map(int, input().split())) for 変数 in range(変数)]でリストに格納する。

入力
3
1 2 3
4 5 6
7 8 9
サンプルコード:sample_1-3-16.py
N = int(input())
x = [list(map(int, input().split())) for i in range(N)]
print(x)
実行結果
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • 文字列をリストに格納する

文字列をリストに格納する場合、リスト = [input().split() for 変数 in range(入力行数)]となる。

入力
a b c
d e f
g h i
サンプルコード:sample_1-3-17.py
x = [input().split() for i in range(3)]
print(x)
実行結果
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
  • 入力行数が指定され、文字列をリストに格納する

入力行数(N = 3)が指定され、文字列をリストに格納する場合、変数 = int(input())で入力行数を格納し、リスト = [input() for 変数 in range(変数)]でリストに格納する。

入力
3
a b c
d e f
g h i
サンプルコード:sample_1-3-18.py
N = int(input())
x = [input().split() for i in range(N)]
print(x)
実行結果
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

第2章 演算

第2章では演算について説明します。

2.1 演算子の優先順位

演算子の優先順位は Python ドキュメントに記載されています。

2.2 算術演算

キーポイント

  • 各演算は下記表の演算子を使用する。
  • 「除算」の結果は 浮動小数点数 となる。
  • 「切り捨て除算」の結果は 整数 となる。(整数除算)
演算子 記述例 意味
+ a + b 加算
- a - b 減算
* a * b 乗算
** a ** b べき乗 / べき根
/ a / b 除算
// a // b 切り捨て除算
% a % b 剰余

加算

加算は+演算子を使用する。

  • 数値を足す
サンプルコード:sample_2-2-1.py
print(1+2)
実行結果
3
  • 変数に格納する
サンプルコード:sample_2-2-2.py
x = 2+3
print(x)
実行結果
5
  • 変数で足す
サンプルコード:sample_2-2-3.py
x = 3
y = 4
print(x+y)
実行結果
7

減算

減算は-演算子を使用する。

  • 数値を引く
サンプルコード:sample_2-2-4.py
print(2-1)
実行結果
1
  • 変数に格納する
サンプルコード:sample_2-2-5.py
x = 4-2
print(x)
実行結果
2
  • 変数で引く
サンプルコード:sample_2-2-6.py
x = 3
y = 6
print(x-y)
実行結果
-3

ABC001 A - 積雪深差 | 提出結果

解答例:answer_2-2-1.py
H1 = int(input())
H2 = int(input())
print(H1-H2)

ABC180 A - box | 提出結果

解答例:answer_2-2-2.py
N, A, B = map(int, input().split())
print(N-A+B)

ABC007 A - 植木算 | 提出結果

解答例:answer_2-2-3.py
n = int(input())
print(n-1)

ABC084 A - New Year | 提出結果

解答例:answer_2-2-4.py
M = int(input())
print(48-M)

ABC008 A - アルバム | 提出結果

解答例:answer_2-2-5.py
S, T = map(int, input().split())
print(T-S+1)

ABC107 A - Train | 提出結果

解答例:answer_2-2-6.py
N, i = map(int, input().split())
print(N-i+1)

ABC202 A - Three Dice | 提出結果

解答例:answer_2-2-7.py
a, b, c = map(int, input().split())
print(21-(a+b+c))

ABC196 A - Difference Max | 提出結果

解答例:answer_2-2-8.py
a, b = map(int, input().split())
c, d = map(int, input().split())
print(b-c)

ABC198 A - Div | 提出結果

解答例:answer_2-2-9.py
N = int(input())
print(N-1)

乗算

乗算は*演算子を使用する。

  • 数値で掛ける
サンプルコード:sample_2-2-7.py
print(2*3)
実行結果
6
  • 変数に格納する
サンプルコード:sample_2-2-8.py
x = 3*4
print(x)
実行結果
12
  • 変数で掛ける
サンプルコード:sample_2-2-9.py
x = 5
y = 6
print(x*y)
実行結果
30

ABC169 A - Multiplication 1 | 提出結果

解答例:answer_2-2-10.py
A, B = map(int, input().split())
print(A*B)

ABC004 A - 流行 | 提出結果

解答例:answer_2-2-11.py
N = int(input())
print(2*N)

ABC232 A - QQ solver | 提出結果

解答例:answer_2-2-12.py
a, b = map(int, input().split("x"))
print(a*b)

ABC389 A - 9x9 | 提出結果

解答例:answer_2-2-13.py
a, b = map(int, input().split("x"))
print(a*b)

ABC184 A - Determinant | 提出結果

解答例:answer_2-2-14.py
a, b = map(int, input().split())
c, d = map(int, input().split())
print(a*d-b*c)

ABC269 A - Anyway Takahashi | 提出結果

解答例:answer_2-2-15.py
a, b, c, d = map(int, input().split())
print((a+b)*(c-d))
print("Takahashi")

ABC163 A - Circle Pond | 提出結果

解答例:answer_2-2-16.py
R = int(input())
print(2*3.14*R)

ABC039 A - 高橋直体 | 提出結果

解答例:answer_2-2-17.py
A, B, C = map(int, input().split())
print(2*(A*B+B*C+C*A))

ABC074 A - Bichrome Cells | 提出結果

解答例:answer_2-2-18.py
N = int(input())
A = int(input())
print(N*N-A)

ABC069 A - K-City | 提出結果

解答例:answer_2-2-19.py
n, m = map(int, input().split())
print((n-1)*(m-1))

ABC106 A - Garden | 提出結果

解答例:answer_2-2-20.py
A, B = map(int, input().split())
print(A*B-(A+B-1))

ABC121 A - White Cells | 提出結果

解答例:answer_2-2-21.py
H, W = map(int, input().split())
h, w = map(int, input().split())
print((H-h)*(W-w))

ABC076 A - Rating Goal | 提出結果

解答例:answer_2-2-22.py
R = int(input())
G = int(input())
print(2*G-R)

ABC182 A - twiblr | 提出結果

解答例:answer_2-2-23.py
A, B = map(int, input().split())
print((2*A+100)-B)

階乗

階乗はimport mathで math モジュールをインポートし、math.factorial(整数)となる。

サンプルコード:sample_2-2-10.py
import math
print(math.factorial(5))  # 120 = 5*4*3*2*1
実行結果
120

ABC273 A - A Recursive Function | 提出結果

解答例:answer_2-2-24.py
import math
N = int(input())
print(math.factorial(N))

べき乗

べき乗は**演算子を使用する。演算は底**指数となる。

  • 数値でべき乗する
サンプルコード:sample_2-2-11.py
print(2**3)
実行結果
8
サンプルコード:sample_2-2-12.py
print(10**9+7)
実行結果
1000000007
  • 変数に格納する
サンプルコード:sample_2-2-13.py
x = 3**2
print(x)
実行結果
9
  • 変数でべき乗する
サンプルコード:sample_2-2-14.py
x = 4
y = 2
print(x**y)
実行結果
16

ABC256 A - 2^N | 提出結果

解答例:answer_2-2-25.py
N = int(input())
print(2**N)

ABC283 A - Power | 提出結果

解答例:answer_2-2-26.py
A, B = map(int, input().split())
print(A**B)

ABC320 A - Leyland Number | 提出結果

解答例:answer_2-2-27.py
A, B = map(int, input().split())
print(A**B+B**A)

ABC387 A - Happy New Year 2025 | 提出結果

解答例:answer_2-2-28.py
A, B = map(int, input().split())
print((A+B)**2)

ABC172 A - Calc | 提出結果

解答例:answer_2-2-29.py
a = int(input())
print(a+a**2+a**3)

ABC134 A - Dodecagon | 提出結果

解答例:answer_2-2-30.py
r = int(input())
print(3*(r**2))

ABC145 A - Circle | 提出結果

解答例:answer_2-2-31.py
r = int(input())
print(r**2)

ABC221 A - Seismic magnitude scales | 提出結果

解答例:answer_2-2-32.py
A, B = map(int, input().split())
print(32**(A-B))

ABC140 A - Password | 提出結果

解答例:answer_2-2-33.py
N = int(input())
print(N**3)

べき根

べき根は**演算子を使用し、底**指数となる。計算結果は 浮動小数点数 となる。

  • 数値でべき根を取る
サンプルコード:sample_2-2-15.py
print(9**(1/2))
実行結果
3.0
サンプルコード:sample_2-2-16.py
print(9**0.5)
実行結果
3.0
  • 変数に格納する
サンプルコード:sample_2-2-17.py
x = 8**(1/3)
print(x)
実行結果
2.0
  • 変数でべき根を取る
サンプルコード:sample_2-2-18.py
x = 8
y = 1/3
print(x**y)
実行結果
2.0

ABC239 A - Horizon | 提出結果 | 提出結果

解答例:answer_2-2-34.py
H = int(input())
print((H*(12800000+H))**(1/2))
解答例:answer_2-2-35.py
H = int(input())
print((H*(12800000+H))**0.5)

除算

除算は/演算子を使用する。除算の結果は 浮動小数点数 となる。ゼロ除算はエラーとなる。

  • 数値で割る
サンプルコード:sample_2-2-19.py
print(5/3)
実行結果
1.6666666666666667
  • 変数に格納する
サンプルコード:sample_2-2-20.py
x = 6/3
print(x)
実行結果
2.0
  • 変数で割る
サンプルコード:sample_2-2-21.py
x = 7
y = 3
print(x/y)
実行結果
2.3333333333333335
  • ゼロ除算はエラーとなる
サンプルコード:sample_2-2-22.py
print(1/0)
実行結果
ZeroDivisionError: division by zero

ABC231 A - Water Pressure | 提出結果

解答例:answer_2-2-36.py
D = int(input())
print(D/100)

ABC211 A - Blood Pressure | 提出結果

解答例:answer_2-2-37.py
A, B = map(int, input().split())
print((A-B)/3+B)

ABC117 A - Entrance Examination | 提出結果

解答例:answer_2-2-38.py
T, X = map(int, input().split())
print(T/X)

ABC205 A - kcal | 提出結果

解答例:answer_2-2-39.py
A, B = map(int, input().split())
print(A*B/100)

ABC193 A - Discount | 提出結果

解答例:answer_2-2-40.py
A, B = map(int, input().split())
print((1-B/A)*100)

切り捨て除算

切り捨て除算は//演算子を使用する。切り捨て除算の結果は小さい方に丸め込まれ、整数 となる。

サンプルコード:sample_2-2-23.py
print(5/3)
print(5//3)
実行結果
1.6666666666666667
1
サンプルコード:sample_2-2-24.py
print(6/3)
print(6//3)
実行結果
2.0
2
サンプルコード:sample_2-2-25.py
print(7/3)
print(7//3)
実行結果
2.3333333333333335
2
サンプルコード:sample_2-2-26.py
print(-5/3)
print(-5//3)
実行結果
-1.6666666666666667
-2
サンプルコード:sample_2-2-27.py
print(-6/3)
print(-6//3)
実行結果
-2.0
-2
サンプルコード:sample_2-2-28.py
print(-7/3)
print(-7//3)
実行結果
-2.3333333333333335
-3

ABC116 A - Right Triangle | 提出結果

解答例:answer_2-2-41.py
AB, BC, CA = map(int, input().split())
print(AB*BC//2)

ABC045 A - 台形 | 提出結果

解答例:answer_2-2-42.py
a, b, h = [int(input()) for i in range(3)]
print((a+b)*h//2)

ABC113 A - Discount Fare | 提出結果

解答例:answer_2-2-43.py
X, Y = map(int, input().split())
print(X+Y//2)

ABC017 A - プロコン | 提出結果

解答例:answer_2-2-44.py
s1, e1 = map(int, input().split())
s2, e2 = map(int, input().split())
s3, e3 = map(int, input().split())
print((s1*e1+s2*e2+s3*e3)//10)

ABC055 A - Restaurant | 提出結果

解答例:answer_2-2-45.py
N = int(input())
print(N*800-N//15*200)

ABC200 A - Century | 提出結果

解答例:answer_2-2-46.py
N = int(input())
print((N+99)//100)

ABC186 A - Brick | 提出結果

解答例:answer_2-2-47.py
N, W = map(int, input().split())
print(N//W)

ABC005 A - おいしいたこ焼きの作り方 | 提出結果

解答例:answer_2-2-48.py
x, y = map(int, input().split())
print(y//x)

ABC089 A - Grouping 2 | 提出結果

解答例:answer_2-2-49.py
N = int(input())
print(N//3)

ABC128 A - Apple Pie | 提出結果

解答例:answer_2-2-50.py
A, P = map(int, input().split())
print((3*A+P)//2)

ABC239 B - Integer Division | 提出結果

解答例:answer_2-2-51.py
X = int(input())
print(X//10)

ABC407 A - Approximation | 提出結果

解答例:answer_2-2-52.py
A, B = map(int, input().split())
print((2*A+B)//(2*B))

切り上げ除算

切り上げ除算はimport mathで math モジュールをインポートし、math.ceil(数値)となる。切り上げ除算の結果は大きい方に丸め込まれる。

サンプルコード:sample_2-2-29.py
import math
print(5/3)
print(math.ceil(5/3))
実行結果
1.6666666666666667
2
サンプルコード:sample_2-2-30.py
import math
print(6/3)
print(math.ceil(6/3))
実行結果
2.0
2
サンプルコード:sample_2-2-31.py
import math
print(7/3)
print(math.ceil(7/3))
実行結果
2.3333333333333335
3
サンプルコード:sample_2-2-32.py
import math
print(-5/3)
print(math.ceil(-5/3))
実行結果
-1.6666666666666667
-1
サンプルコード:sample_2-2-33.py
import math
print(-6/3)
print(math.ceil(-6/3))
実行結果
-2.0
-2
サンプルコード:sample_2-2-34.py
import math
print(-7/3)
print(math.ceil(-7/3))
実行結果
-2.3333333333333335
-2

ABC082 A - Round Up the Mean | 提出結果

解答例:answer_2-2-53.py
import math
a, b = map(int, input().split())
print(math.ceil((a+b)/2))

ABC157 A - Duplex Printing | 提出結果

解答例:answer_2-2-54.py
import math
N = int(input())
print(math.ceil(N/2))

ABC009 A - 引越し作業 | 提出結果

解答例:answer_2-2-55.py
import math
N = int(input())
print(math.ceil(N/2))

ABC036 A - お茶 | 提出結果

解答例:answer_2-2-56.py
import math
A, B = map(int, input().split())
print(math.ceil(B/A))

剰余

剰余は%演算子を使用する。ゼロ剰余はエラーとなる。

サンプルコード:sample_2-2-35.py
print(6 % 3)
実行結果
0
サンプルコード:sample_2-2-36.py
print(7 % 3)
実行結果
1
サンプルコード:sample_2-2-37.py
print(8 % 3)
実行結果
2
サンプルコード:sample_2-2-38.py
print(-6 % 3)
実行結果
0
サンプルコード:sample_2-2-39.py
print(-7 % 3)
実行結果
2
サンプルコード:sample_2-2-40.py
print(-8 % 3)
実行結果
1

ゼロ剰余はエラーとなる。

サンプルコード:sample_2-2-41.py
print(1 % 0)
実行結果
ZeroDivisionError: integer division or modulo by zero

ABC011 A - 来月は何月? | 提出結果

解答例:answer_2-2-57.py
N = int(input())
print((N % 12)+1)

ABC057 A - Remaining Time | 提出結果

解答例:answer_2-2-58.py
A, B = map(int, input().split())
print((A+B) % 24)

ABC087 A - Buying Sweets | 提出結果

解答例:answer_2-2-59.py
X, A, B = [int(input()) for i in range(3)]
print((X-A) % B)

ABC192 A - Star | 提出結果

解答例:answer_2-2-60.py
X = int(input())
print(100-(X % 100))

ABC363 A - Piling Up | 提出結果

解答例:answer_2-2-61.py
R = int(input())
print(100-(R % 100))

ABC227 A - Last Card | 提出結果

解答例:answer_2-2-62.py
N, K, A = map(int, input().split())
print(((A+K-2) % N)+1)

ABC041 B - 直方体 | 提出結果

解答例:answer_2-2-63.py
A, B, C = map(int, input().split())
print((A*B*C) % (10**9+7))

ABC266 B - Modulo Number | 提出結果

解答例:answer_2-2-64.py
N = int(input())
print(N % 998244353)

2.3 論理演算

論理演算は下記の表の通りとなる。

演算子 記述例 意味
and a and b a と b が真であれば真
or a or b a または b が真であれば真
not not a a が偽であれば真
サンプルコード:sample_2-3-1.py
print(True and True)
実行結果
True
サンプルコード:sample_2-3-2.py
print(True and False)
実行結果
False
サンプルコード:sample_2-3-3.py
print(False and False)
実行結果
False
サンプルコード:sample_2-3-4.py
print(True or True)
実行結果
True
サンプルコード:sample_2-3-5.py
print(True or False)
実行結果
True
サンプルコード:sample_2-3-6.py
print(False or False)
実行結果
False
サンプルコード:sample_2-3-7.py
print(not True)
実行結果
False
サンプルコード:sample_2-3-8.py
print(not False)
実行結果
True

2.4 比較演算

比較演算は下記の表の通りとなる。

演算子 記述例 意味
== a == b a が b と等しい
!= a != b a が b と等しくない
> a > b a が b より大きい
>= a >= b a が b 以上
< a < b a が b より小さい
<= a <= b a が b 以下

数値

サンプルコード:sample_2-4-1.py
print(10 == 10)
実行結果
True
サンプルコード:sample_2-4-2.py
print(10 == 20)
実行結果
False
サンプルコード:sample_2-4-3.py
print(10 != 20)
実行結果
True
サンプルコード:sample_2-4-4.py
print(10 != 10)
実行結果
False
サンプルコード:sample_2-4-5.py
print(20 > 10)
実行結果
True
サンプルコード:sample_2-4-6.py
print(10 > 20)
実行結果
False
サンプルコード:sample_2-4-7.py
print(10 >= 10)
実行結果
True
サンプルコード:sample_2-4-8.py
print(10 >= 20)
実行結果
False
サンプルコード:sample_2-4-9.py
print(10 < 20)
実行結果
True
サンプルコード:sample_2-4-10.py
print(20 < 10)
実行結果
False
サンプルコード:sample_2-4-11.py
print(10 <= 10)
実行結果
True
サンプルコード:sample_2-4-12.py
print(20 <= 10)
実行結果
False

文字列

サンプルコード:sample_2-4-13.py
print("a" == "a")
実行結果
True
サンプルコード:sample_2-4-14.py
print("a" == "b")
実行結果
False
サンプルコード:sample_2-4-15.py
print("a" != "b")
実行結果
True
サンプルコード:sample_2-4-16.py
print("a" != "a")
実行結果
False
サンプルコード:sample_2-4-17.py
print("b" > "a")
実行結果
True
サンプルコード:sample_2-4-18.py
print("a" > "b")
実行結果
False
サンプルコード:sample_2-4-19.py
print("a" >= "a")
実行結果
True
サンプルコード:sample_2-4-20.py
print("a" >= "b")
実行結果
False
サンプルコード:sample_2-4-21.py
print("a" < "b")
実行結果
True
サンプルコード:sample_2-4-22.py
print("b" < "a")
実行結果
False
サンプルコード:sample_2-4-23.py
print("a" <= "a")
実行結果
True
サンプルコード:sample_2-4-24.py
print("b" <= "a")
実行結果
False

2.5 所属検査演算(in演算)

所属検査演算(in演算)は下記の表の通りとなる。

演算子 記述例 意味
in a in b a が b に含まれる
not in a not in b a が b に含まれない

文字列

部分文字列の所属を評価する。

サンプルコード:sample_2-5-1.py
print("a" in "abc")
実行結果
True
サンプルコード:sample_2-5-2.py
print("z" in "abc")
実行結果
False
サンプルコード:sample_2-5-3.py
print("ab" in "abc")
実行結果
True
サンプルコード:sample_2-5-4.py
print("ac" in "abc")
実行結果
False
サンプルコード:sample_2-5-5.py
print("abc" in "abc")
実行結果
True
サンプルコード:sample_2-5-6.py
print("abcd" in "abc")
実行結果
False
サンプルコード:sample_2-5-7.py
print("z" not in "abc")
実行結果
True

リスト

要素の所属を評価する。

サンプルコード:sample_2-5-8.py
print("a" in ["a", "b", "c"])
実行結果
True
サンプルコード:sample_2-5-9.py
print("z" in ["a", "b", "c"])
実行結果
False
サンプルコード:sample_2-5-10.py
print("ab" in ["a", "b", "c"])
実行結果
False
サンプルコード:sample_2-5-11.py
print("z" not in ["a", "b", "c"])
実行結果
True
サンプルコード:sample_2-5-12.py
print(10 in [10, 20, 30])
実行結果
True
サンプルコード:sample_2-5-13.py
print(90 not in [10, 20, 30])
実行結果
True

集合

要素の所属を評価する。

サンプルコード:sample_2-5-14.py
print("a" in {"a", "b", "c"})
実行結果
True
サンプルコード:sample_2-5-15.py
print("z" in {"a", "b", "c"})
実行結果
False
サンプルコード:sample_2-5-16.py
print("ab" in {"a", "b", "c"})
実行結果
False
サンプルコード:sample_2-5-17.py
print("z" not in {"a", "b", "c"})
実行結果
True
サンプルコード:sample_2-5-18.py
print(10 in {10, 20, 30})
実行結果
True
サンプルコード:sample_2-5-19.py
print(90 not in {10, 20, 30})
実行結果
True

2.6 ビット演算

ビット演算は下記の表の通りとなる。

演算子 記述例 意味
& a & b a と b のビット単位の論理積(AND)
| a | b a と b のビット単位の論理和(OR)
^ a ^ b a と b のビット単位の排他的論理和(XOR)

論理積(AND)

ビット単位の論理積は&を使用する。

サンプルコード:sample_2-6-1.py
print(1 & 1)  # 1 = 0b0001 = 0b0001 & 0b0001
実行結果
1
サンプルコード:sample_2-6-2.py
print(1 & 2)  # 0 = 0b0000 = 0b0001 & 0b0010
実行結果
0
サンプルコード:sample_2-6-3.py
print(2 & 3)  # 2 = 0b0010 = 0b0010 & 0b0011
実行結果
2

論理和(OR)

ビット単位の論理和は|を使用する。

サンプルコード:sample_2-6-4.py
print(1 | 2)  # 3 = 0b0011 = 0b0001 | 0b0010
実行結果
3
サンプルコード:sample_2-6-5.py
print(1 | 2 | 4)  # 7 = 0b0111 = 0b0001 | 0b0010 | 0b0100
実行結果
7
サンプルコード:sample_2-6-6.py
print(1 | 2 | 4 | 8)  # 15 = 0b1111 = 0b0001 | 0b0010 | 0b0100 | 0b1000
実行結果
15

ABC270 A - 1-2-4 Test | 提出結果

解答例:answer_2-6-1.py
a, b = map(int, input().split())
print(a | b)

排他的論理和(XOR)

ビット単位の排他的論理和は^を使用する。

サンプルコード:sample_2-6-7.py
print(1 ^ 1)  # 0 = 0b0000 = 0b0001 ^ 0b0001
実行結果
0
サンプルコード:sample_2-6-8.py
print(1 ^ 1 ^ 2)  # 2 = 0b0010 = 0b0001 ^ 0b0001 ^ 0b0010
実行結果
2
サンプルコード:sample_2-6-9.py
print(1 ^ 1 ^ 2 ^ 2)  # 0 = 0b0000 = 0b0001 ^ 0b0001 ^ 0b0010 ^ 0b0010
実行結果
0
サンプルコード:sample_2-6-10.py
print(1 ^ 2)  # 3 = 0b0011 = 0b0001 ^ 0b0010
実行結果
3
サンプルコード:sample_2-6-11.py
print(1 ^ 2 ^ 4)  # 7 = 0b0111 = 0b0001 ^ 0b0010 ^ 0b0100
実行結果
7
サンプルコード:sample_2-6-12.py
print(1 ^ 2 ^ 4 ^ 8)  # 15 = 0b1111 = 0b0001 ^ 0b0010 ^ 0b0100 ^ 0b1000
実行結果
15

ABC075 A - One out of Three | 提出結果

解答例:answer_2-6-2.py
A, B, C = map(int, input().split())
print(A ^ B ^ C)

ABC027 A - 長方形 | 提出結果

解答例:answer_2-6-3.py
l1, l2, l3 = map(int, input().split())
print(l1 ^ l2 ^ l3)

ABC246 A - Four Points | 提出結果

解答例:answer_2-6-4.py
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
x3, y3 = map(int, input().split())
print(x1 ^ x2 ^ x3, y1 ^ y2 ^ y3)

ABC148 A - Round One | 提出結果

解答例:answer_2-6-5.py
A = int(input())
B = int(input())
print(A ^ B)

ABC213 A - Bitwise Exclusive Or | 提出結果

解答例:answer_2-6-6.py
A, B = map(int, input().split())
print(A ^ B)

第3章 代入文

第3章では代入文について説明します。

3.1 代入文

代入文は下記の通りに記述することができる。

サンプルコード:sample_3-1-1.py
x, y = 1, 2
print(x, y)
実行結果
1 2
サンプルコード:sample_3-1-2.py
x, y = 1, 2
x, y = y, x
print(x, y)
実行結果
2 1

ABC012 A - スワップ | 提出結果

解答例:answer_3-1-1.py
A, B = map(int, input().split())
A, B = B, A
print(A, B)

ABC161 A - ABC Swap | 提出結果 | 提出結果

解答例:answer_3-1-2.py
X, Y, Z = map(int, input().split())
A, B, C = X, Y, Z
A, B = B, A
A, C = C, A
print(A, B, C)
解答例:answer_3-1-3.py
X, Y, Z = map(int, input().split())
A, B, C = X, Y, Z
A, B, C = C, A, B
print(A, B, C)

3.2 累算代入文

累算代入文は下記の表の通りとなる。

演算子 記述例 等式
+= a += b a = a + b
-= a -= b a = a - b
*= a *= b a = a * b
**= a **= b a = a ** b
/= a /= b a = a / b
//= a //= b a = a // b
%= a %= b a = a % b
サンプルコード:sample_3-2-1.py
x = 2
x += 1  # x = x+1
print(x)
実行結果
3
サンプルコード:sample_3-2-2.py
x = 2
x -= 1  # x = x-1
print(x)
実行結果
1
サンプルコード:sample_3-2-3.py
x = 2
x *= 3  # x = x*3
print(x)
実行結果
6
サンプルコード:sample_3-2-4.py
x = 2
x **= 3  # x = x**3
print(x)
実行結果
8
サンプルコード:sample_3-2-5.py
x = 6
x /= 3  # x = x/3
print(x)
実行結果
2.0
サンプルコード:sample_3-2-6.py
x = 6
x //= 3  # x = x//3
print(x)
実行結果
2
サンプルコード:sample_3-2-7.py
x = 5
x %= 3  # x = x % 3
print(x)
実行結果
2

第4章 制御構文

第4章では制御構文について説明します。

4.1 分岐処理

キーポイント

  • 分岐処理は「if文」を使用する。
  • 特定の文字列、数値が含まれているかを評価する場合はin演算子を使用する。
  • 条件式を複数組み合わせることができる。

if文

数値

サンプルコード:sample_4-1-1.py
x = 10
if x == 10:
    print("x == 10")
if x == 20:
    print("x == 20")
実行結果
x == 10
サンプルコード:sample_4-1-2.py
x = 20
if x == 10:
    print("x == 10")
if x == 20:
    print("x == 20")
実行結果
x == 20

ABC020 A - クイズ | 提出結果

解答例:answer_4-1-1.py
Q = int(input())
if Q == 1:
    print("ABC")
if Q == 2:
    print("chokudai")

ABC178 A - Not | 提出結果

解答例:answer_4-1-2.py
x = int(input())
if x == 0:
    print(1)
if x == 1:
    print(0)

ABC112 A - Programming Education | 提出結果

解答例:answer_4-1-3.py
N = int(input())
if N == 1:
    print("Hello World")
if N == 2:
    A = int(input())
    B = int(input())
    print(A+B)

ABC204 A - Rock-paper-scissors | 提出結果

解答例:answer_4-1-4.py
x, y = map(int, input().split())
if x == 0 and y == 0:
    print(0)
if x == 0 and y == 1:
    print(2)
if x == 0 and y == 2:
    print(1)
if x == 1 and y == 0:
    print(2)
if x == 1 and y == 1:
    print(1)
if x == 1 and y == 2:
    print(0)
if x == 2 and y == 0:
    print(1)
if x == 2 and y == 1:
    print(0)
if x == 2 and y == 2:
    print(2)

ABC355 A - Who Ate the Cake? | 提出結果

解答例:answer_4-1-5.py
A, B = map(int, input().split())
if A == B:
    print(-1)
if A == 1 and B == 2:
    print(3)
if A == 1 and B == 3:
    print(2)
if A == 2 and B == 1:
    print(3)
if A == 2 and B == 3:
    print(1)
if A == 3 and B == 1:
    print(2)
if A == 3 and B == 2:
    print(1)

ABC250 A - Adjacent Squares | 提出結果 | 提出結果

解答例:answer_4-1-6.py
H, W = map(int, input().split())
R, C = map(int, input().split())
count = 4
if C == 1:
    count -= 1
if C == W:
    count -= 1
if R == 1:
    count -= 1
if R == H:
    count -= 1
print(count)
解答例:answer_4-1-7.py
H, W = map(int, input().split())
R, C = map(int, input().split())
count = 0
if C != 1:
    count += 1
if C != W:
    count += 1
if R != 1:
    count += 1
if R != H:
    count += 1
print(count)

文字列

サンプルコード:sample_4-1-3.py
x = "a"
if x == "a":
    print("x == a")
if x == "b":
    print("x == b")
実行結果
x == a
サンプルコード:sample_4-1-4.py
x = "b"
if x == "a":
    print("x == a")
if x == "b":
    print("x == b")
実行結果
x == b

ABC166 A - A?C | 提出結果

解答例:answer_4-1-8.py
S = input()
if S == "ABC":
    print("ARC")
if S == "ARC":
    print("ABC")

ABC122 A - Double Helix | 提出結果

解答例:answer_4-1-9.py
b = input()
if b == "A":
    print("T")
if b == "T":
    print("A")
if b == "C":
    print("G")
if b == "G":
    print("C")

ABC393 A - Poisonous Oyster | 提出結果

解答例:answer_4-1-10.py
t, a = input().split()
if t == "sick" and a == "sick":
    print(1)
if t == "sick" and a == "fine":
    print(2)
if t == "fine" and a == "sick":
    print(3)
if t == "fine" and a == "fine":
    print(4)

ABC056 A - HonestOrDishonest | 提出結果

解答例:answer_4-1-11.py
a, b = input().split()
if a == "H" and b == "H":
    print("H")
if a == "H" and b == "D":
    print("D")
if a == "D" and b == "H":
    print("D")
if a == "D" and b == "D":
    print("H")

if文 / elif節 / else節

if文はif 条件式:で条件文を書く。条件式がTrueの場合、条件文の中の処理がされる。条件式を2つ以上記載する場合、elif 条件式:で条件文を書く。どの条件式もTrueでない場合、else:の処理がされる。

数値

サンプルコード:sample_4-1-5.py
x = 10
if x == 10:
    print("x == 10")
else:
    print("else")
実行結果
x == 10
サンプルコード:sample_4-1-6.py
x = 20
if x == 10:
    print("x == 10")
else:
    print("else")
実行結果
else
サンプルコード:sample_4-1-7.py
x = 10
if x == 10:
    print("x == 10")
elif x == 20:
    print("x == 20")
else:
    print("else")
実行結果
x == 10
サンプルコード:sample_4-1-8.py
x = 20
if x == 10:
    print("x == 10")
elif x == 20:
    print("x == 20")
else:
    print("else")
実行結果
x == 20
サンプルコード:sample_4-1-9.py
x = 30
if x == 10:
    print("x == 10")
elif x == 20:
    print("x == 20")
else:
    print("else")
実行結果
else
サンプルコード:sample_4-1-10.py
x = 10
y = 20
if x < y:
    print("x < y")
elif x == y:
    print("x == y")
else:
    print("else")
実行結果
x < y
サンプルコード:sample_4-1-11.py
x = 20
y = 20
if x < y:
    print("x < y")
elif x == y:
    print("x == y")
else:
    print("else")
実行結果
x == y
サンプルコード:sample_4-1-12.py
x = 20
y = 10
if x < y:
    print("x < y")
elif x == y:
    print("x == y")
else:
    print("else")
実行結果
else

ABC020 A - クイズ | 提出結果

解答例:answer_4-1-12.py
Q = int(input())
if Q == 1:
    print("ABC")
else:
    print("chokudai")

ABC178 A - Not | 提出結果

解答例:answer_4-1-13.py
x = int(input())
if x == 0:
    print(1)
else:
    print(0)

ABC053 A - ABC/ARC | 提出結果

解答例:answer_4-1-14.py
x = int(input())
if x < 1200:
    print("ABC")
else:
    print("ARC")

ABC099 A - ABD | 提出結果

解答例:answer_4-1-15.py
N = int(input())
if N < 1000:
    print("ABC")
else:
    print("ABD")

ABC174 A - Air Conditioner | 提出結果

解答例:answer_4-1-16.py
X = int(input())
if X >= 30:
    print("Yes")
else:
    print("No")

ABC138 A - Red or Not | 提出結果

解答例:answer_4-1-17.py
a = int(input())
s = input()
if a >= 3200:
    print(s)
else:
    print("red")

ABC112 A - Programming Education | 提出結果

解答例:answer_4-1-18.py
N = int(input())
if N == 1:
    print("Hello World")
else:
    A = int(input())
    B = int(input())
    print(A+B)

ABC334 A - Christmas Present | 提出結果

解答例:answer_4-1-19.py
B, G = map(int, input().split())
if B > G:
    print("Bat")
else:
    print("Glove")

ABC034 A - テスト | 提出結果

解答例:answer_4-1-20.py
x, y = map(int, input().split())
if x < y:
    print("Better")
else:
    print("Worse")

ABC130 A - Rounding | 提出結果

解答例:answer_4-1-21.py
X, A = map(int, input().split())
if X < A:
    print(0)
else:
    print(10)

ABC164 A - Sheep and Wolves | 提出結果

解答例:answer_4-1-22.py
S, W = map(int, input().split())
if W >= S:
    print("unsafe")
else:
    print("safe")

ABC063 A - Restricted | 提出結果

解答例:answer_4-1-23.py
A, B = map(int, input().split())
if A+B < 10:
    print(A+B)
else:
    print("error")

ABC091 A - Two Coins | 提出結果

解答例:answer_4-1-24.py
A, B, C = map(int, input().split())
if A+B >= C:
    print("Yes")
else:
    print("No")

ABC058 A - ι⊥l | 提出結果

解答例:answer_4-1-25.py
a, b, c = map(int, input().split())
if b-a == c-b:
    print("YES")
else:
    print("NO")

ABC150 A - 500 Yen Coins | 提出結果

解答例:answer_4-1-26.py
K, X = map(int, input().split())
if 500*K >= X:
    print("Yes")
else:
    print("No")

ABC199 A - Square Inequality | 提出結果

解答例:answer_4-1-27.py
A, B, C = map(int, input().split())
if A**2+B**2 < C**2:
    print("Yes")
else:
    print("No")

ABC177 A - Don't be late | 提出結果

解答例:answer_4-1-28.py
D, T, S = map(int, input().split())
if D <= S*T:
    print("Yes")
else:
    print("No")

ABC152 A - AC or WA | 提出結果

解答例:answer_4-1-29.py
N, M = map(int, input().split())
if N == M:
    print("Yes")
else:
    print("No")

ABC100 A - Happy Birthday! | 提出結果

解答例:answer_4-1-30.py
A, B = map(int, input().split())
if A <= 8 and B <= 8:
    print("Yay!")
else:
    print(":(")

ABC343 A - Wrong Answer | 提出結果

解答例:answer_4-1-31.py
A, B = map(int, input().split())
if A+B == 0:
    print(1)
else:
    print(0)

ABC096 A - Day of Takahashi | 提出結果

解答例:answer_4-1-32.py
a, b = map(int, input().split())
if a > b:
    print(a-1)
else:
    print(a)

ABC104 A - Rated for Me | 提出結果

解答例:answer_4-1-33.py
R = int(input())
if R < 1200:
    print("ABC")
elif R < 2800:
    print("ARC")
else:
    print("AGC")

ABC028 A - テスト評価 | 提出結果

解答例:answer_4-1-34.py
N = int(input())
if N < 60:
    print("Bad")
elif N < 90:
    print("Good")
elif N < 100:
    print("Great")
else:
    print("Perfect")

ABC214 A - New Generation ABC | 提出結果

解答例:answer_4-1-35.py
N = int(input())
if N <= 125:
    print(4)
elif N <= 211:
    print(6)
else:
    print(8)

ABC219 A - AtCoder Quiz 2 | 提出結果

解答例:answer_4-1-36.py
X = int(input())
if X < 40:
    print(40-X)
elif X < 70:
    print(70-X)
elif X < 90:
    print(90-X)
else:
    print("expert")

ABC363 A - Piling Up | 提出結果

解答例:answer_4-1-37.py
R = int(input())
if R < 100:
    print(100-R)
elif R < 200:
    print(200-R)
else:
    print(300-R)

ABC127 A - Ferris Wheel | 提出結果

解答例:answer_4-1-38.py
a, b = map(int, input().split())
if 12 < a:
    print(b)
elif 5 < a:
    print(b//2)
else:
    print(0)

ABC212 A - Alloy | 提出結果

解答例:answer_4-1-39.py
A, B = map(int, input().split())
if B == 0:
    print("Gold")
elif A == 0:
    print("Silver")
else:
    print("Alloy")

ABC030 A - 勝率計算 | 提出結果

解答例:answer_4-1-40.py
A, B, C, D = map(int, input().split())
if B/A > D/C:
    print("TAKAHASHI")
elif B/A < D/C:
    print("AOKI")
else:
    print("DRAW")

ABC366 A - Election 2 | 提出結果

解答例:answer_4-1-41.py
N, T, A = map(int, input().split())
if T > N/2 or A > N/2:
    print("Yes")
else:
    print("No")

ABC083 A - Libra | 提出結果

解答例:answer_4-1-42.py
A, B, C, D = map(int, input().split())
if A+B > C+D:
    print("Left")
elif A+B == C+D:
    print("Balanced")
else:
    print("Right")

ABC392 A - Shuffled Equation | 提出結果

解答例:answer_4-1-43.py
a, b, c = map(int, input().split())
if a*b == c or b*c == a or c*a == b:
    print("Yes")
else:
    print("No")

ABC370 A - Raise Both Hands | 提出結果

解答例:answer_4-1-44.py
L, R = map(int, input().split())
if L == 1 and R == 0:
    print("Yes")
elif L == 0 and R == 1:
    print("No")
else:
    print("Invalid")

ABC065 A - Expired? | 提出結果

解答例:answer_4-1-45.py
X, A, B = map(int, input().split())
if X < B-A:
    print("dangerous")
elif A < B:
    print("safe")
else:
    print("delicious")

ABC369 A - 369 | 提出結果

解答例:answer_4-1-46.py
A, B = map(int, input().split())
if A == B:
    print(1)
elif (A-B) % 2 == 1:
    print(2)
else:
    print(3)

ABC190 A - Very Very Primitive Game | 提出結果

解答例:answer_4-1-47.py
A, B, C = map(int, input().split())
if A < B:
    print("Aoki")
elif A > B:
    print("Takahashi")
elif C == 0:
    print("Aoki")
else:
    print("Takahashi")

ABC245 A - Good morning | 提出結果

解答例:answer_4-1-48.py
A, B, C, D = map(int, input().split())
if A < C:
    print("Takahashi")
elif A > C:
    print("Aoki")
elif B <= D:
    print("Takahashi")
else:
    print("Aoki")

ABC242 A - T-shirt | 提出結果

解答例:answer_4-1-49.py
A, B, C, X = map(int, input().split())
if X <= A:
    print(1)
elif X > B:
    print(0)
else:
    print(C/(B-A))

ABC194 A - I Scream | 提出結果

解答例:answer_4-1-50.py
A, B = map(int, input().split())
if A+B >= 15 and B >= 8:
    print(1)
elif A+B >= 10 and B >= 3:
    print(2)
elif A+B >= 3:
    print(3)
else:
    print(4)

ABC075 A - One out of Three | 提出結果

解答例:answer_4-1-51.py
A, B, C = map(int, input().split())
if A == B:
    print(C)
elif B == C:
    print(A)
elif C == A:
    print(B)

ABC203 A - Chinchirorin | 提出結果

解答例:answer_4-1-52.py
a, b, c = map(int, input().split())
if a == b:
    print(c)
elif b == c:
    print(a)
elif c == a:
    print(b)
else:
    print(0)

ABC209 A - Counting | 提出結果

解答例:answer_4-1-53.py
A, B = map(int, input().split())
if B-A+1 > 0:
    print(B-A+1)
else:
    print(0)

ABC183 A - ReLU | 提出結果

解答例:answer_4-1-54.py
x = int(input())
if x > 0:
    print(x)
else:
    print(0)

ABC072 A - Sandglass2 | 提出結果

解答例:answer_4-1-55.py
X, t = map(int, input().split())
if X-t > 0:
    print(X-t)
else:
    print(0)

ABC143 A - Curtain | 提出結果

解答例:answer_4-1-56.py
A, B = map(int, input().split())
if A-2*B > 0:
    print(A-2*B)
else:
    print(0)

ABC136 A - Transfer | 提出結果

解答例:answer_4-1-57.py
A, B, C = map(int, input().split())
water = C-(A-B)
if water > 0:
    print(water)
else:
    print(0)

ABC233 A - 10yen Stamp | 提出結果

解答例:answer_4-1-58.py
import math
X, Y = map(int, input().split())
if Y-X > 0:
    print(math.ceil((Y-X)/10))
else:
    print(0)

ABC156 A - Beginner | 提出結果

解答例:answer_4-1-59.py
N, R = map(int, input().split())
if N >= 10:
    print(R)
else:
    print(R+100*(10-N))

ABC024 A - 動物園 | 提出結果

解答例:answer_4-1-60.py
A, B, C, K = map(int, input().split())
S, T = map(int, input().split())
if S+T < K:
    print(A*S+B*T)
else:
    print(A*S+B*T-(S+T)*C)

ABC044 A - 高橋君とホテルイージー | 提出結果

解答例:answer_4-1-61.py
N, K, X, Y = [int(input()) for i in range(4)]
if N <= K:
    print(N*X)
else:
    print(K*X+(N-K)*Y)

ABC210 A - Cabbages | 提出結果

解答例:answer_4-1-62.py
N, A, X, Y = map(int, input().split())
if N < A:
    print(N*X)
else:
    print(A*X+(N-A)*Y)

ABC259 A - Growth Record | 提出結果

解答例:answer_4-1-63.py
N, M, X, T, D = map(int, input().split())
if M >= X:
    print(T)
else:
    print(T-(X-M)*D)

ABC240 A - Edge Checker | 提出結果 | 提出結果

解答例:answer_4-1-64.py
a, b = map(int, input().split())
if (a == b-1) or (a == 1 and b == 10):
    print("Yes")
else:
    print("No")
解答例:answer_4-1-65.py
a, b = map(int, input().split())
if b-a == 1 or b-a == 9:
    print("Yes")
else:
    print("No")

ABC238 A - Exponential or Quadratic | 提出結果

解答例:answer_4-1-66.py
n = int(input())
if n == 2 or n == 3 or n == 4:
    print("No")
else:
    print("Yes")

ABC406 A - Not Acceptable | 提出結果

解答例:answer_4-1-67.py
A, B, C, D = map(int, input().split())
if (C < A) or (C == A and D < B):
    print("Yes")
else:
    print("No")

ABC331 A - Tomorrow | 提出結果

解答例:answer_4-1-68.py
M, D = map(int, input().split())
y, m, d = map(int, input().split())
if d == D and m == M:
    print(y+1, 1, 1)
elif d == D:
    print(y, m+1, 1)
else:
    print(y, m, d+1)

ABC086 A - Product | 提出結果

解答例:answer_4-1-69.py
a, b = map(int, input().split())
if a*b % 2 == 0:
    print("Even")
else:
    print("Odd")

ABC400 A - ABC400 Party | 提出結果

解答例:answer_4-1-70.py
A = int(input())
if 400 % A == 0:
    print(400//A)
else:
    print(-1)

ABC102 A - Multiple of 2 and N | 提出結果

解答例:answer_4-1-71.py
N = int(input())
if N % 2 == 0:
    print(N)
else:
    print(N*2)

ABC135 A - Harmony | 提出結果

解答例:answer_4-1-72.py
A, B = map(int, input().split())
if (A+B) % 2 == 0:
    print((A+B)//2)
else:
    print("IMPOSSIBLE")

ABC181 A - Heavy Rotation | 提出結果

解答例:answer_4-1-73.py
N = int(input())
if N % 2 == 0:
    print("White")
else:
    print("Black")

ABC118 A - B +/- A | 提出結果

解答例:answer_4-1-74.py
A, B = map(int, input().split())
if B % A == 0:
    print(A+B)
else:
    print(B-A)

ABC195 A - Health M Death | 提出結果

解答例:answer_4-1-75.py
M, H = map(int, input().split())
if H % M == 0:
    print("Yes")
else:
    print("No")

ABC016 A - 12月6日 | 提出結果

解答例:answer_4-1-76.py
M, D = map(int, input().split())
if M % D == 0:
    print("YES")
else:
    print("NO")

ABC088 A - Infinite Coins | 提出結果

解答例:answer_4-1-77.py
N = int(input())
A = int(input())
if N % 500 <= A:
    print("Yes")
else:
    print("No")

ABC035 A - テレビ | 提出結果

解答例:answer_4-1-78.py
W, H = map(int, input().split())
if W*H % 144 == 0:
    print("16:9")
else:
    print("4:3")

ABC105 A - AtCoder Crackers | 提出結果

解答例:answer_4-1-79.py
N, K = map(int, input().split())
if N % K == 0:
    print(0)
else:
    print(1)

ABC142 A - Odds of Oddness | 提出結果

解答例:answer_4-1-80.py
N = int(input())
if N % 2 == 0:
    print(0.5)
else:
    print(((N//2)+1)/N)

ABC302 A - Attack | 提出結果

解答例:answer_4-1-81.py
A, B = map(int, input().split())
if A % B == 0:
    print(A//B)
else:
    print(A//B+1)

ABC153 A - Serval vs Monster | 提出結果

解答例:answer_4-1-82.py
H, A = map(int, input().split())
if H % A == 0:
    print(H//A)
else:
    print(H//A+1)

ABC176 A - Takoyaki | 提出結果

解答例:answer_4-1-83.py
N, X, T = map(int, input().split())
if N % X == 0:
    print(T*(N//X))
else:
    print(T*(N//X+1))

ABC067 A - Sharing Cookies | 提出結果

解答例:answer_4-1-84.py
A, B = map(int, input().split())
if A % 3 == 0 or B % 3 == 0 or (A+B) % 3 == 0:
    print("Possible")
else:
    print("Impossible")

ABC262 A - World Cup | 提出結果

解答例:answer_4-1-85.py
Y = int(input())
if Y % 4 == 0:
    print(Y+2)
elif Y % 4 == 1:
    print(Y+1)
elif Y % 4 == 2:
    print(Y)
else:
    print(Y+3)

ABC365 A - Leap Year | 提出結果

解答例:answer_4-1-86.py
Y = int(input())
if Y % 4 != 0:
    print(365)
elif Y % 4 == 0 and Y % 100 != 0:
    print(366)
elif Y % 100 == 0 and Y % 400 != 0:
    print(365)
elif Y % 400 == 0:
    print(366)

ABC054 A - One Card Poker | 提出結果

解答例:answer_4-1-87.py
A, B = map(int, input().split())
if A == B:
    print("Draw")
elif (A+13) % 15 < (B+13) % 15:
    print("Bob")
else:
    print("Alice")

ABC223 A - Exact Price | 提出結果

解答例:answer_4-1-88.py
X = int(input())
if X % 100 == 0 and X != 0:
    print("Yes")
else:
    print("No")

ABC173 A - Payment | 提出結果

解答例:answer_4-1-89.py
N = int(input())
if N % 1000 == 0:
    print(0)
else:
    print(1000-(N % 1000))

ABC265 A - Apple | 提出結果

解答例:answer_4-1-90.py
X, Y, N = map(int, input().split())
if X < Y/3:
    print(X*N)
else:
    print(Y*(N//3)+X*(N % 3))

ABC367 A - Shout Everyday | 提出結果

解答例:answer_4-1-91.py
A, B, C = map(int, input().split())
if (B < C and not B < A < C) or (C < B and C < A < B):
    print("Yes")
else:
    print("No")

ABC220 A - Find Multiple | 提出結果

解答例:answer_4-1-92.py
A, B, C = map(int, input().split())
mod = B-(B % C)
if A <= mod:
    print(mod)
else:
    print(-1)

ABC243 A - Shampoo | 提出結果

解答例:answer_4-1-93.py
V, A, B, C = map(int, input().split())
V = V % (A+B+C)
if V-A < 0:
    print("F")
elif V-(A+B) < 0:
    print("M")
else:
    print("T")

ABC014 A - けんしょう先生のお菓子配り | 提出結果

解答例:answer_4-1-94.py
a = int(input())
b = int(input())
if a % b != 0:
    print(b-(a % b))
else:
    print(0)

文字列

サンプルコード:sample_4-1-13.py
x = "a"
if x == "a":
    print("x == a")
else:
    print("else")
実行結果
x == a
サンプルコード:sample_4-1-14.py
x = "b"
if x == "a":
    print("x == a")
else:
    print("else")
実行結果
else
サンプルコード:sample_4-1-15.py
x = "a"
if x == "a":
    print("x == a")
elif x == "b":
    print("x == b")
else:
    print("else")
実行結果
x == a
サンプルコード:sample_4-1-16.py
x = "b"
if x == "a":
    print("x == a")
elif x == "b":
    print("x == b")
else:
    print("else")
実行結果
x == b
サンプルコード:sample_4-1-17.py
x = "c"
if x == "a":
    print("x == a")
elif x == "b":
    print("x == b")
else:
    print("else")
実行結果
else
サンプルコード:sample_4-1-18.py
x = "a"
y = "b"
if x < y:
    print("x < y")
elif x == y:
    print("x == y")
else:
    print("else")
実行結果
x < y
サンプルコード:sample_4-1-19.py
x = "a"
y = "a"
if x < y:
    print("x < y")
elif x == y:
    print("x == y")
else:
    print("else")
実行結果
x == y
サンプルコード:sample_4-1-20.py
x = "b"
y = "a"
if x < y:
    print("x < y")
elif x == y:
    print("x == y")
else:
    print("else")
実行結果
else

ABC215 A - Your First Judge | 提出結果

解答例:answer_4-1-95.py
S = input()
if S == "Hello,World!":
    print("AC")
else:
    print("WA")

ABC166 A - A?C | 提出結果

解答例:answer_4-1-96.py
S = input()
if S == "ARC":
    print("ABC")
else:
    print("ARC")

ABC122 A - Double Helix | 提出結果

解答例:answer_4-1-97.py
b = input()
if b == "A":
    print("T")
elif b == "T":
    print("A")
elif b == "C":
    print("G")
else:
    print("C")

ABC358 A - Welcome to AtCoder Land | 提出結果 | 提出結果

解答例:answer_4-1-98.py
S, T = input().split()
if S == "AtCoder" and T == "Land":
    print("Yes")
else:
    print("No")
解答例:answer_4-1-99.py
ST = input()
if ST == "AtCoder Land":
    print("Yes")
else:
    print("No")

ABC393 A - Poisonous Oyster | 提出結果

解答例:answer_4-1-100.py
t, a = input().split()
if t == "sick" and a == "sick":
    print(1)
elif t == "sick":
    print(2)
elif a == "sick":
    print(3)
else:
    print(4)

ABC078 A - HEX | 提出結果

解答例:answer_4-1-101.py
X, Y = input().split()
if X < Y:
    print("<")
elif X == Y:
    print("=")
else:
    print(">")

ABC217 A - Lexicographic Order | 提出結果

解答例:answer_4-1-102.py
S, T = input().split()
if S < T:
    print("Yes")
else:
    print("No")

ABC119 A - Still TBD | 提出結果

解答例:answer_4-1-103.py
S = input()
if S <= "2019/04/30":
    print("Heisei")
else:
    print("TBD")

ABC154 A - Remaining Balls | 提出結果

解答例:answer_4-1-104.py
S, T = input().split()
A, B = map(int, input().split())
U = input()
if S == U:
    print(A-1, B)
else:
    print(A, B-1)

ABC160 A - Coffee | 提出結果

解答例:answer_4-1-105.py
a, b, c, d, e, f = input()
if c == d and e == f:
    print("Yes")
else:
    print("No")

ABC070 A - Palindromic Number | 提出結果

解答例:answer_4-1-106.py
a, b, c = input()
if a == c:
    print("Yes")
else:
    print("No")

ABC371 A - Jiro | 提出結果

解答例:answer_4-1-107.py
AB, AC, BC = input().split()
if (AB == ">" and AC == "<") or (AC == ">" and AB == "<"):
    print("A")
elif (AB == "<" and BC == "<") or (BC == ">" and AB == ">"):
    print("B")
else:
    print("C")

ABC056 A - HonestOrDishonest | 提出結果

解答例:answer_4-1-108.py
a, b = input().split()
if a == "H" and b == "H":
    print("H")
elif a == "H" and b == "D":
    print("D")
elif a == "D" and b == "H":
    print("D")
else:
    print("H")

ABC229 A - First Grid | 提出結果

解答例:answer_4-1-109.py
S1 = input()
S2 = input()
if (S1 == "#." and S2 == ".#") or (S1 == ".#" and S2 == "#."):
    print("No")
else:
    print("Yes")

if文 / in演算

文字列や要素の所属を評価する場合、in演算子を使用する。if 探すデータ in 探されるデータとなる。

文字列

サンプルコード:sample_4-1-21.py
if "a" in "abc":
    print("a in abc")
else:
    print("else")
実行結果
a in abc
サンプルコード:sample_4-1-22.py
if "ab" in "abc":
    print("ab in abc")
else:
    print("else")
実行結果
ab in abc
サンプルコード:sample_4-1-23.py
if "z" in "abc":
    print("z in abc")
else:
    print("else")
実行結果
else

ABC049 A - 居合を終え、青い絵を覆う | 提出結果

解答例:answer_4-1-110.py
c = input()
if c in "aiueo":
    print("vowel")
else:
    print("consonant")

ABC114 A - 753 | 提出結果

解答例:answer_4-1-111.py
X = input()
if X in "753":
    print("YES")
else:
    print("NO")

ABC162 A - Lucky 7 | 提出結果

解答例:answer_4-1-112.py
N = input()
if "7" in N:
    print("Yes")
else:
    print("No")

ABC073 A - September 9 | 提出結果

解答例:answer_4-1-113.py
N = input()
if "9" in N:
    print("Yes")
else:
    print("No")

ABC006 A - 世界のFizzBuzz | 提出結果

解答例:answer_4-1-114.py
N = input()
if N in "369":
    print("YES")
else:
    print("NO")

ABC171 A - αlphabet | 提出結果 | 提出結果

解答例:answer_4-1-115.py
a = input()
if a in "abcdefghijklmnopqrstuvwxyz":
    print("a")
else:
    print("A")
解答例:answer_4-1-116.py
a = input()
if a in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    print("A")
else:
    print("a")

ABC327 A - ab | 提出結果

解答例:answer_4-1-117.py
N = int(input())
S = input()
if "ab" in S or "ba" in S:
    print("Yes")
else:
    print("No")

ABC298 A - Job Interview | 提出結果

解答例:answer_4-1-118.py
N = int(input())
S = input()
if "o" in S and "x" not in S:
    print("Yes")
else:
    print("No")

ABC296 A - Alternately | 提出結果

解答例:answer_4-1-119.py
N = int(input())
S = input()
if "MM" in S or "FF" in S:
    print("No")
else:
    print("Yes")

ABC109 A - ABC333 | 提出結果 | 提出結果

解答例:answer_4-1-120.py
A, B = input().split()
if "2" in A or "2" in B:
    print("No")
else:
    print("Yes")
解答例:answer_4-1-121.py
AB = input()
if "2" in AB:
    print("No")
else:
    print("Yes")

リスト

サンプルコード:sample_4-1-24.py
if "a" in ["a", "b", "c"]:
    print("a in list")
else:
    print("else")
実行結果
a in list
サンプルコード:sample_4-1-25.py
if "ab" in ["a", "b", "c"]:
    print("ab in list")
else:
    print("else")
実行結果
else
サンプルコード:sample_4-1-26.py
if 10 in [10, 20, 30]:
    print("10 in list")
else:
    print("else")
実行結果
10 in list

ABC312 A - Chord | 提出結果

解答例:answer_4-1-122.py
S = input()
if S in ["ACE", "BDF", "CEG", "DFA", "EGB", "FAC", "GBD"]:
    print("Yes")
else:
    print("No")

ABC377 A - Rearranging ABC | 提出結果

解答例:answer_4-1-123.py
S = input()
if S in ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]:
    print("Yes")
else:
    print("No")

ABC309 A - Nine | 提出結果

解答例:answer_4-1-124.py
A, B = map(int, input().split())
X = [[1, 2], [2, 3], [4, 5], [5, 6], [7, 8], [8, 9]]
if [A, B] in X:
    print("Yes")
else:
    print("No")

ABC390 A - 12435 | 提出結果

解答例:answer_4-1-125.py
A = list(map(int, input().split()))
if A in [[2, 1, 3, 4, 5], [1, 3, 2, 4, 5], [1, 2, 4, 3, 5], [1, 2, 3, 5, 4]]:
    print("Yes")
else:
    print("No")

ABC285 A - Edge Checker 2 | 提出結果

解答例:answer_4-1-126.py
a, b = map(int, input().split())
graph = [[1, 2], [1, 3], [2, 4], [2, 5], [3, 6], [3, 7], [4, 8],
         [4, 9], [5, 10], [5, 11], [6, 12], [6, 13], [7, 14], [7, 15]]
if [a, b] in graph:
    print("Yes")
else:
    print("No")

集合

サンプルコード:sample_4-1-27.py
if "a" in {"a", "b", "c"}:
    print("a in set")
else:
    print("else")
実行結果
a in set
サンプルコード:sample_4-1-28.py
if "ab" in {"a", "b", "c"}:
    print("ab in set")
else:
    print("else")
実行結果
else
サンプルコード:sample_4-1-29.py
if 10 in {10, 20, 30}:
    print("10 in set")
else:
    print("else")
実行結果
10 in set

ABC309 A - Nine | 提出結果

解答例:answer_4-1-127.py
A, B = map(int, input().split())
X = {(1, 2), (2, 3), (4, 5), (5, 6), (7, 8), (8, 9)}
if (A, B) in X:
    print("Yes")
else:
    print("No")

ABC285 A - Edge Checker 2 | 提出結果

解答例:answer_4-1-128.py
a, b = map(int, input().split())
graph = {(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7), (4, 8),
         (4, 9), (5, 10), (5, 11), (6, 12), (6, 13), (7, 14), (7, 15)}
if (a, b) in graph:
    print("Yes")
else:
    print("No")

複数条件式

条件式を複数組み合わせることができる。

数値

サンプルコード:sample_4-1-30.py
x = 10
y = 10
z = 10
if x == y == z:
    print("x == y == z")
else:
    print("else")
実行結果
x == y == z
サンプルコード:sample_4-1-31.py
x = 10
y = 20
z = 30
if x < y < z:
    print("x < y < z")
else:
    print("else")
実行結果
x < y < z

ABC401 A - Status Code | 提出結果

解答例:answer_4-1-129.py
S = int(input())
if 200 <= S <= 299:
    print("Success")
else:
    print("Failure")

ABC061 A - Between Two Integers | 提出結果

解答例:answer_4-1-130.py
A, B, C = map(int, input().split())
if A <= C <= B:
    print("Yes")
else:
    print("No")

ABC237 A - Not Overflow | 提出結果

解答例:answer_4-1-131.py
N = int(input())
if -2**31 <= N < 2**31:
    print("Yes")
else:
    print("No")

ABC326 A - 2UP3DOWN | 提出結果

解答例:answer_4-1-132.py
X, Y = map(int, input().split())
if -3 <= Y-X <= 2:
    print("Yes")
else:
    print("No")

ABC253 A - Median? | 提出結果

解答例:answer_4-1-133.py
a, b, c = map(int, input().split())
if a <= b <= c or c <= b <= a:
    print("Yes")
else:
    print("No")

ABC352 A - AtCoder Line | 提出結果

解答例:answer_4-1-134.py
N, X, Y, Z = map(int, input().split())
if X < Z < Y or X > Z > Y:
    print("Yes")
else:
    print("No")

ABC219 A - AtCoder Quiz 2 | 提出結果

解答例:answer_4-1-135.py
X = int(input())
if 0 <= X < 40:
    print(40-X)
elif 40 <= X < 70:
    print(70-X)
elif 70 <= X < 90:
    print(90-X)
else:
    print("expert")

ABC079 A - Good Integer | 提出結果

解答例:answer_4-1-136.py
a, b, c, d = map(int, input())
if a == b == c or b == c == d:
    print("Yes")
else:
    print("No")

ABC131 A - Security | 提出結果

解答例:answer_4-1-137.py
a, b, c, d = map(int, input())
if a != b != c != d:
    print("Good")
else:
    print("Bad")

ABC208 A - Rolling Dice | 提出結果

解答例:answer_4-1-138.py
A, B = map(int, input().split())
if A <= B <= 6*A:
    print("Yes")
else:
    print("No")

ABC144 A - 9x9 | 提出結果

解答例:answer_4-1-139.py
A, B = map(int, input().split())
if 1 <= A <= 9 and 1 <= B <= 9:
    print(A*B)
else:
    print(-1)

ABC191 A - Vanishing Pitch | 提出結果

解答例:answer_4-1-140.py
V, T, S, D = map(int, input().split())
if V*T <= D <= V*S:
    print("No")
else:
    print("Yes")

ABC094 A - Cats and Dogs | 提出結果 | 提出結果

解答例:answer_4-1-141.py
A, B, X = map(int, input().split())
if A <= X <= A+B:
    print("YES")
else:
    print("NO")
解答例:answer_4-1-142.py
A, B, X = map(int, input().split())
if 0 <= X-A <= B:
    print("YES")
else:
    print("NO")

ABC405 A - Is it rated? | 提出結果

解答例:answer_4-1-143.py
R, X = map(int, input().split())
if (X == 1 and 1600 <= R <= 2999) or (X == 2 and 1200 <= R <= 2399):
    print("Yes")
else:
    print("No")

ABC228 A - On and Off | 提出結果

解答例:answer_4-1-144.py
S, T, X = map(int, input().split())
if S < T:
    if S <= X < T:
        print("Yes")
    else:
        print("No")
else:
    if X < T or S <= X:
        print("Yes")
    else:
        print("No")

ABC238 A - Exponential or Quadratic | 提出結果

解答例:answer_4-1-145.py
n = int(input())
if 2 <= n <= 4:
    print("No")
else:
    print("Yes")

文字列

サンプルコード:sample_4-1-32.py
x = "abc"
y = "abc"
z = "abc"
if x == y == z:
    print("x == y == z")
else:
    print("else")
実行結果
x == y == z
サンプルコード:sample_4-1-33.py
x = "a"
y = "b"
z = "c"
if x < y < z:
    print("x < y < z")
else:
    print("else")
実行結果
x < y < z

ABC189 A - Slot | 提出結果

解答例:answer_4-1-146.py
a, b, c = input()
if a == b == c:
    print("Won")
else:
    print("Lost")

ABC079 A - Good Integer | 提出結果

解答例:answer_4-1-147.py
a, b, c, d = input()
if a == b == c or b == c == d:
    print("Yes")
else:
    print("No")

ABC350 A - Past ABCs | 提出結果

解答例:answer_4-1-148.py
S = input()
if "ABC001" <= S <= "ABC349" and S != "ABC316":
    print("Yes")
else:
    print("No")

ABC131 A - Security | 提出結果

解答例:answer_4-1-149.py
a, b, c, d = input()
if a != b != c != d:
    print("Good")
else:
    print("Bad")

4.2 反復処理

キーポイント

  • 反復処理は「for文」と「while文」がある。
  • in演算を使った「for文」はfor 変数 in リスト:となる。
  • range関数を使った「for文」はfor 変数 in range(初期値, 終了値):となる。初期値を指定しない場合、変数は 0 から始まる。
  • 「for文」でelse節を使用することができる。
  • 「while文」はwhile 条件式:となる。条件式がTrueの場合、while文の中の処理を続ける。

for文 / in演算

リスト

in演算を使ったfor文はfor 変数 in リスト:となる。

サンプルコード:sample_4-2-1.py
x = [1, 2, 3]
for i in x:
    print(i)
実行結果
1
2
3
サンプルコード:sample_4-2-2.py
x = ["a", "b", "c"]
for i in x:
    print(i)
実行結果
a
b
c

ABC272 A - Integer Sum | 提出結果

解答例:answer_4-2-1.py
N = int(input())
A = list(map(int, input().split()))
total = 0
for a in A:
    total += a
print(total)

ABC202 A - Three Dice | 提出結果

解答例:answer_4-2-2.py
abc = list(map(int, input().split()))
total = 0
for dice in abc:
    total += 7-dice
print(total)

ABC147 A - Blackjack | 提出結果

解答例:answer_4-2-3.py
A = list(map(int, input().split()))
total = 0
for a in A:
    total += a
if total >= 22:
    print("bust")
else:
    print("win")

ABC330 A - Counting Passes | 提出結果

解答例:answer_4-2-4.py
N, L = map(int, input().split())
A = list(map(int, input().split()))
count = 0
for a in A:
    if a >= L:
        count += 1
print(count)

ABC328 A - Not Too Hard | 提出結果

解答例:answer_4-2-5.py
N, X = map(int, input().split())
S = list(map(int, input().split()))
total = 0
for s in S:
    if s <= X:
        total += s
print(total)

ABC410 A - G1 | 提出結果

解答例:answer_4-2-6.py
N = int(input())
A = list(map(int, input().split()))
K = int(input())
ans = 0
for a in A:
    if K <= a:
        ans += 1
print(ans)

ABC300 A - N-choice question | 提出結果

解答例:answer_4-2-7.py
N, A, B = map(int, input().split())
C = list(map(int, input().split()))
idx = 1
for c in C:
    if A+B == c:
        print(idx)
    else:
        idx += 1

ABC294 A - Filter | 提出結果

解答例:answer_4-2-8.py
N = int(input())
A = list(map(int, input().split()))
for a in A:
    if a % 2 == 0:
        print(a, end=" ")

ABC347 A - Divisible | 提出結果

解答例:answer_4-2-9.py
N, K = map(int, input().split())
A = list(map(int, input().split()))
for a in A:
    if a % K == 0:
        print(a//K, end=" ")

文字列

サンプルコード:sample_4-2-3.py
x = "abc"
for i in x:
    print(i)
実行結果
a
b
c
サンプルコード:sample_4-2-4.py
x = "012"
for i in x:
    print(i)
実行結果
0
1
2

ABC329 A - Spread | 提出結果

解答例:answer_4-2-10.py
S = input()
for s in S:
    print(s, end=" ")

ABC382 A - Daily Cookie | 提出結果

解答例:answer_4-2-11.py
N, D = map(int, input().split())
S = input()
a = 0
for s in S:
    if s == "@":
        a += 1
print(N-a+D)

ABC279 A - wwwvvvvvv | 提出結果

解答例:answer_4-2-12.py
S = input()
count = 0
for s in S:
    if s == "v":
        count += 1
    if s == "w":
        count += 2
print(count)

for文 / range関数

range関数を使ったfor文はfor 変数 in range(初期値, 終了値, ステップ数):となる。初期値を指定しない場合、変数は 0 から始まる。

サンプルコード:sample_4-2-5.py
for i in range(5):
    print(i)
実行結果
0
1
2
3
4
サンプルコード:sample_4-2-6.py
for i in range(2, 5):
    print(i)
実行結果
2
3
4
サンプルコード:sample_4-2-7.py
for i in range(2, 5, 2):
    print(i)
実行結果
2
4
サンプルコード:sample_4-2-8.py
for i in range(3, -1, -1):
    print(i)
実行結果
3
2
1
0

ABC288 A - Many A+B Problems | 提出結果

解答例:answer_4-2-13.py
N = int(input())
for i in range(N):
    A, B = map(int, input().split())
    print(A+B)

ABC008 A - アルバム | 提出結果

解答例:answer_4-2-14.py
S, T = map(int, input().split())
picture = 0
for i in range(S, T+1):
    picture += 1
print(picture)

ABC043 A - キャンディーとN人の子供イージー | 提出結果

解答例:answer_4-2-15.py
N = int(input())
candy = 0
for i in range(1, N+1):
    candy += i
print(candy)

ABC281 A - Count Down | 提出結果 | 提出結果

解答例:answer_4-2-16.py
N = int(input())
for i in range(N+1):
    print(N-i)
解答例:answer_4-2-17.py
N = int(input())
for i in range(N, -1, -1):
    print(i)

ABC340 A - Arithmetic Progression | 提出結果

解答例:answer_4-2-18.py
A, B, D = map(int, input().split())
for i in range(A, B+1, D):
    print(i, end=" ")

ABC021 A - 足し算 | 提出結果

解答例:answer_4-2-19.py
N = int(input())
print(N)
for i in range(N):
    print(1)

ABC332 A - Online Shopping | 提出結果

解答例:answer_4-2-20.py
N, S, K = map(int, input().split())
total = 0
for i in range(N):
    P, Q = map(int, input().split())
    total += P*Q
if total >= S:
    print(total)
else:
    print(total+K)

ABC337 A - Scoreboard | 提出結果

解答例:answer_4-2-21.py
N = int(input())
takahashi, aoki = 0, 0
for i in range(N):
    X, Y = map(int, input().split())
    takahashi += X
    aoki += Y
if takahashi > aoki:
    print("Takahashi")
elif takahashi < aoki:
    print("Aoki")
else:
    print("Draw")

ABC300 A - N-choice question | 提出結果

解答例:answer_4-2-22.py
N, A, B = map(int, input().split())
C = list(map(int, input().split()))
for i in range(N):
    if A+B == C[i]:
        print(i+1)

ABC277 A - ^{-1} | 提出結果

解答例:answer_4-2-23.py
N, X = map(int, input().split())
P = list(map(int, input().split()))
for i in range(N):
    if P[i] == X:
        print(i+1)

ABC317 A - Potions | 提出結果

解答例:answer_4-2-24.py
N, H, X = map(int, input().split())
P = list(map(int, input().split()))
for i in range(N):
    if H+P[i] >= X:
        print(i+1)
        break

ABC412 A - Task Failed Successfully | 提出結果

解答例:answer_4-2-25.py
N = int(input())
ans = 0
for i in range(N):
    A, B = map(int, input().split())
    if A < B:
        ans += 1
print(ans)

ABC318 A - Full Moon | 提出結果

解答例:answer_4-2-26.py
N, M, P = map(int, input().split())
count = 0
for i in range(N):
    if M <= N:
        count += 1
        M += P
print(count)

ABC357 A - Sanitize Hands | 提出結果

解答例:answer_4-2-27.py
N, M = map(int, input().split())
H = list(map(int, input().split()))
count = 0
for i in range(N):
    M -= H[i]
    if M < 0:
        break
    else:
        count += 1
print(count)

ABC022 A - Best Body | 提出結果

解答例:answer_4-2-28.py
N, S, T = map(int, input().split())
W = int(input())
day = 0
if S <= W <= T:
    day += 1
for i in range(N-1):
    A = int(input())
    W += A
    if S <= W <= T:
        day += 1
print(day)

ABC003 A - AtCoder社の給料 | 提出結果

解答例:answer_4-2-29.py
N = int(input())
salary = 0
for i in range(1, N+1):
    salary += i*10000*(1/N)
print(salary)

ABC249 A - Jogging | 提出結果

解答例:answer_4-2-30.py
A, B, C, D, E, F, X = map(int, input().split())
takahashi = 0
aoki = 0
for i in range(X):
    if i % (A+C) < A:
        takahashi += B
    if i % (D+F) < D:
        aoki += E
if takahashi > aoki:
    print("Takahashi")
elif takahashi < aoki:
    print("Aoki")
else:
    print("Draw")

for文 / else節

for文でelse節を使用することができる。for文で反復処理をbreakせずに終了した場合、else節が実行される。

サンプルコード:sample_4-2-9.py
x = False
for i in range(5):
    if x:
        print(True)
        break
else:
    print(False)
実行結果
False

ABC396 A - Triple Four | 提出結果

解答例:answer_4-2-31.py
N = int(input())
A = list(map(int, input().split()))
for i in range(N-2):
    if A[i] == A[i+1] == A[i+2]:
        print("Yes")
        break
else:
    print("No")

ABC220 A - Find Multiple | 提出結果

解答例:answer_4-2-32.py
A, B, C = map(int, input().split())
for i in range(A, B+1):
    if i % C == 0:
        print(i)
        break
else:
    print(-1)

ABC165 A - We Love Golf | 提出結果

解答例:answer_4-2-33.py
K = int(input())
A, B = map(int, input().split())
for i in range(A, B+1):
    if i % K == 0:
        print("OK")
        break
else:
    print("NG")

ABC295 A - Probably English | 提出結果

解答例:answer_4-2-34.py
N = int(input())
W = input().split()
S = {"and", "not", "that", "the", "you"}
for w in W:
    if w in S:
        print("Yes")
        break
else:
    print("No")

ABC296 A - Alternately | 提出結果 | 提出結果

解答例:answer_4-2-35.py
N = int(input())
S = input()
for i in range(N-1):
    if S[i] != S[i+1]:
        continue
    else:
        print("No")
        break
else:
    print("Yes")
解答例:answer_4-2-36.py
N = int(input())
S = input()
for i in range(N-1):
    if S[i] == S[i+1]:
        print("No")
        break
else:
    print("Yes")

ABC395 A - Strictly Increasing? | 提出結果 | 提出結果

解答例:answer_4-2-37.py
N = int(input())
A = list(map(int, input().split()))
for i in range(N-1):
    if A[i] < A[i+1]:
        continue
    else:
        print("No")
        break
else:
    print("Yes")
解答例:answer_4-2-38.py
N = int(input())
A = list(map(int, input().split()))
for i in range(N-1):
    if A[i] >= A[i+1]:
        print("No")
        break
else:
    print("Yes")

ABC321 A - 321-like Checker | 提出結果 | 提出結果

解答例:answer_4-2-39.py
N = input()
for i in range(len(N)-1):
    if N[i] > N[i+1]:
        continue
    else:
        print("No")
        break
else:
    print("Yes")
解答例:answer_4-2-40.py
N = input()
for i in range(len(N)-1):
    if N[i] <= N[i+1]:
        print("No")
        break
else:
    print("Yes")

ABC323 A - Weak Beats | 提出結果 | 提出結果

解答例:answer_4-2-41.py
S = input()
for i in range(1, 16, 2):
    if S[i] == "0":
        continue
    else:
        print("No")
        break
else:
    print("Yes")
解答例:answer_4-2-42.py
S = input()
for i in range(1, 16, 2):
    if S[i] != "0":
        print("No")
        break
else:
    print("Yes")

ABC409 A - Conflict | 提出結果

解答例:answer_4-2-43.py
N = int(input())
T = input()
A = input()
for i in range(N):
    if T[i] == A[i] == "o":
        print("Yes")
        break
else:
    print("No")

ABC408 A - Timeout | 提出結果

解答例:answer_4-2-44.py
N, S = map(int, input().split())
T = list(map(int, input().split()))
p = 0
for t in T:
    if t-p > S:
        print("No")
        break
    p = t
else:
    print("Yes")

while文

while文はwhile 条件式:となる。条件式がTrueの場合、while文の中の処理を続ける。

サンプルコード:sample_4-2-10.py
i = 0
while i < 5:
    print(i)
    i += 1
実行結果
0
1
2
3
4

ABC281 A - Count Down | 提出結果

解答例:answer_4-2-45.py
N = int(input())
while N >= 0:
    print(N)
    N -= 1

ABC340 A - Arithmetic Progression | 提出結果

解答例:answer_4-2-46.py
A, B, D = map(int, input().split())
while A <= B:
    print(A, end=" ")
    A += D

ABC318 A - Full Moon | 提出結果

解答例:answer_4-2-47.py
N, M, P = map(int, input().split())
count = 0
while M <= N:
    count += 1
    M += P
print(count)

ABC354 A - Exponential Plant | 提出結果

解答例:answer_4-2-48.py
H = int(input())
now = 0
day = 0
while now <= H:
    now += 2**day
    day += 1
print(day)

ABC032 A - 高橋君と青木君の好きな数 | 提出結果 | 提出結果

解答例:answer_4-2-49.py
a, b, n = [int(input()) for i in range(3)]
while n % a != 0 or n % b != 0:
    n += 1
print(n)
解答例:answer_4-2-50.py
a, b, n = [int(input()) for i in range(3)]
while not (n % a == 0 and n % b == 0):
    n += 1
print(n)

第5章 組み込み型

第5章では組み込み型について説明します。

5.1 整数(int)

整数への変換

整数への変換はint(数値)で整数に変換される。

サンプルコード:sample_5-1-1.py
print(int(2.9))
実行結果
2
サンプルコード:sample_5-1-2.py
print(int(3.0))
実行結果
3
サンプルコード:sample_5-1-3.py
print(int(3.1))
実行結果
3
サンプルコード:sample_5-1-4.py
x = -2.9
print(int(x))
実行結果
-2
サンプルコード:sample_5-1-5.py
x = -3.0
print(int(x))
実行結果
-3
サンプルコード:sample_5-1-6.py
x = -3.1
print(int(x))
実行結果
-3
サンプルコード:sample_5-1-7.py
x = "10"
print(int(x))
実行結果
10
サンプルコード:sample_5-1-8.py
x = "010"
print(int(x))
実行結果
10

ABC232 A - QQ solver | 提出結果

解答例:answer_5-1-1.py
a, x, b = input()
print(int(a)*int(b))

ABC389 A - 9x9 | 提出結果

解答例:answer_5-1-2.py
a, x, b = input()
print(int(a)*int(b))

ABC050 A - Addition and Subtraction Easy | 提出結果 | 提出結果

解答例:answer_5-1-3.py
A, op, B = input().split()
A = int(A)
B = int(B)
if op == "+":
    print(A+B)
if op == "-":
    print(A-B)
解答例:answer_5-1-4.py
A, op, B = input().split()
if op == "+":
    print(int(A)+int(B))
if op == "-":
    print(int(A)-int(B))

ABC125 A - Biscuit Generator | 提出結果

解答例:answer_5-1-5.py
A, B, T = map(int, input().split())
print(int(B*((T+0.5)//A)))

ABC206 A - Maxi-Buying | 提出結果

解答例:answer_5-1-6.py
N = int(input())
if int(1.08*N) < 206:
    print("Yay!")
elif int(1.08*N) == 206:
    print("so-so")
else:
    print(":(")

ABC039 B - エージェント高橋君 | 提出結果

解答例:answer_5-1-7.py
X = int(input())
print(int(X**(1/4)))

5.2 浮動小数点数(float)

浮動小数点数への変換

浮動小数点数への変換はfloat(数値)で浮動小数点数に変換される。

サンプルコード:sample_5-2-1.py
x = 10
print(float(x))
実行結果
10.0
サンプルコード:sample_5-2-2.py
x = "10"
print(float(x))
実行結果
10.0

ABC397 A - Thermometer | 提出結果

解答例:answer_5-2-1.py
X = float(input())
if 38.0 <= X:
    print(1)
elif 37.5 <= X < 38.0:
    print(2)
else:
    print(3)

ABC226 A - Round decimals | 提出結果

解答例:answer_5-2-2.py
X = float(input())
print(int(X+0.5))

5.3 文字列(str)

キーポイント

  • 文字列の定義は文字列をダブルクォーテーション"、またはシングルクォーテーション'で囲う。
  • 文字列への変換はstr(データ)で文字列に変換される。
  • 文字列の連結は+演算子を使用する。
  • 文字列の繰り返しは*演算子を使用する。
  • 文字列の参照は文字列[インデックス]となる。
  • 文字列の探索はindexメソッドを使用する。
  • 文字列を前方から検索する場合はfindメソッドを使用する。
  • 文字列を後方から検索する場合はrfindメソッドを使用する。
  • 文字列のカウントはcountメソッドを使用する。
  • 文字列のスライスは文字列[開始のインデックス:終了のインデックス:ステップ数]となる。
  • 文字列の逆順は文字列[::-1]となる。
  • 文字列の置換はreplaceメソッドを使用する。
  • 文字列の大文字変換はupperメソッドを使用する。
  • 文字列の小文字変換はlowerメソッドを使用する。
  • 文字列の大文字判定はisupperメソッドを使用する。
  • 文字列の小文字判定はislowerメソッドを使用する。
  • 文字列のゼロ埋めはzfillメソッドを使用する。
  • 文字列のフォーマットはフォーマット済み文字列リテラルを使用する。

文字列の定義

文字列の定義は文字列をダブルクォーテーション"、またはシングルクォーテーション'で囲う。

サンプルコード:sample_5-3-1.py
print("Hello World!")
実行結果
Hello World!
サンプルコード:sample_5-3-2.py
x = "Hello World!"
print(x)
実行結果
Hello World!

文字列への変換

文字列への変換はstr(データ)で文字列に変換される。

サンプルコード:sample_5-3-3.py
x = 10
print(str(x))
実行結果
10

ABC248 A - Lacked Number | 提出結果

解答例:answer_5-3-1.py
S = input()
for i in range(10):
    if str(i) not in S:
        print(i)
        break

文字列の連結

文字列の連結は+演算子を使用する。

サンプルコード:sample_5-3-4.py
print("Hello"+"World")
実行結果
HelloWorld
サンプルコード:sample_5-3-5.py
x = "Hello"
y = "World"
print(x+y)
実行結果
HelloWorld

ABC029 A - 複数形 | 提出結果

解答例:answer_5-3-2.py
W = input()
print(W+"s")

ABC010 A - ハンドルネーム | 提出結果

解答例:answer_5-3-3.py
S = input()
print(S+"pp")

ABC068 A - ABCxxx | 提出結果

解答例:answer_5-3-4.py
N = input()
print("ABC"+N)

ABC149 A - Strings | 提出結果

解答例:answer_5-3-5.py
S, T = input().split()
print(T+S)

ABC325 A - Takahashi san | 提出結果

解答例:answer_5-3-6.py
S, T = input().split()
print(S+" san")

ABC344 A - Spoiler | 提出結果

解答例:answer_5-3-7.py
a, b, c = input().split("|")
print(a+c)

ABC216 A - Signed Difficulty | 提出結果

解答例:answer_5-3-8.py
X, Y = input().split(".")
if 0 <= int(Y) <= 2:
    print(X+"-")
if 3 <= int(Y) <= 6:
    print(X)
if 7 <= int(Y) <= 9:
    print(X+"+")

ABC230 A - AtCoder Quiz 3 | 提出結果

解答例:answer_5-3-9.py
N = int(input())
if N <= 9:
    print("AGC00"+str(N))
elif N <= 41:
    print("AGC0"+str(N))
else:
    print("AGC0"+str(N+1))

ABC258 A - When? | 提出結果

解答例:answer_5-3-10.py
K = int(input())
if K < 60:
    if K < 10:
        print("21:0"+str(K))
    else:
        print("21:"+str(K))
else:
    if K-60 < 10:
        print("22:0"+str(K-60))
    else:
        print("22:"+str(K-60))

ABC379 A - Cyclic | 提出結果

解答例:answer_5-3-11.py
a, b, c = input()
print(b+c+a, c+a+b)

ABC235 A - Rotate | 提出結果

解答例:answer_5-3-12.py
a, b, c = input()
abc = a+b+c
bca = b+c+a
cab = c+a+b
print(int(abc)+int(bca)+int(cab))

ABC064 A - RGB Cards | 提出結果

解答例:answer_5-3-13.py
r, g, b = input().split()
if int(r+g+b) % 4 == 0:
    print("YES")
else:
    print("NO")

ABC306 A - Echo | 提出結果

解答例:answer_5-3-14.py
N = int(input())
S = input()
ans = ""
for s in S:
    ans += s+s
print(ans)

ABC372 A - delete . | 提出結果

解答例:answer_5-3-15.py
S = input()
ans = ""
for s in S:
    if s != ".":
        ans += s
print(ans)

ABC348 A - Penalty Kick | 提出結果

解答例:answer_5-3-16.py
N = int(input())
s = ""
for i in range(1, N+1):
    if i % 3 == 0:
        s += "x"
    else:
        s += "o"
print(s)

ABC384 A - aaaadaa | 提出結果 | 提出結果

解答例:answer_5-3-17.py
N, c1, c2 = input().split()
S = input()
ans = ""
for s in S:
    if s != c1:
        ans += c2
    else:
        ans += c1
print(ans)
解答例:answer_5-3-18.py
N, c1, c2 = input().split()
N = int(N)
S = input()
ans = ""
for i in range(N):
    if S[i] != c1:
        ans += c2
    else:
        ans += c1
print(ans)

文字列の繰り返し

文字列の繰り返しは*演算子を使用する。

サンプルコード:sample_5-3-6.py
print("HelloWorld!"*2)
実行結果
HelloWorld!HelloWorld!
サンプルコード:sample_5-3-7.py
print("1"*5)
実行結果
11111

ABC336 A - Long Loong | 提出結果

解答例:answer_5-3-19.py
N = int(input())
print("L"+"o"*N+"ng")

ABC341 A - Print 341 | 提出結果 | 提出結果

解答例:answer_5-3-20.py
N = int(input())
print("1"+"01"*N)
解答例:answer_5-3-21.py
N = int(input())
print("10"*N+"1")

ABC333 A - Three Threes | 提出結果 | 提出結果

解答例:answer_5-3-22.py
N = input()
print(N*int(N))
解答例:answer_5-3-23.py
N = int(input())
print(str(N)*N)

ABC115 A - Christmas Eve Eve Eve | 提出結果

解答例:answer_5-3-24.py
D = int(input())
print("Christmas"+" Eve"*(25-D))

ABC398 A - Doors in the Center | 提出結果

解答例:answer_5-3-25.py
N = int(input())
if N % 2 == 0:
    print("-"*(N//2-1)+"=="+"-"*(N//2-1))
else:
    print("-"*(N//2)+"="+"-"*(N//2))

ABC296 A - Alternately | 提出結果

解答例:answer_5-3-26.py
N = int(input())
S = input()
if S in "MF"*51:
    print("Yes")
else:
    print("No")

ABC381 A - 11/22 String | 提出結果

解答例:answer_5-3-27.py
N = int(input())
S = input()
if S == "1"*(N//2)+"/"+"2"*(N//2):
    print("Yes")
else:
    print("No")

文字列の参照

文字列の参照は文字列[インデックス]となる。範囲外の参照はIndexErrorが返却される。

サンプルコード:sample_5-3-8.py
x = "abc"
print(x[0], x[1], x[2])
実行結果
a b c
サンプルコード:sample_5-3-9.py
x = "abc"
print(x[-1], x[-2], x[-3])
実行結果
c b a
サンプルコード:sample_5-3-10.py
x = "abc"
print(x[3])
実行結果
IndexError: string index out of range

ABC232 A - QQ solver | 提出結果

解答例:answer_5-3-28.py
S = input()
print(int(S[0])*int(S[2]))

ABC389 A - 9x9 | 提出結果

解答例:answer_5-3-29.py
S = input()
print(int(S[0])*int(S[2]))

ABC388 A - ?UPC | 提出結果

解答例:answer_5-3-30.py
S = input()
print(S[0]+"UPC")

ABC048 A - AtCoder *** Contest | 提出結果

解答例:answer_5-3-31.py
s = input()
print("A"+s[8]+"C")

ABC090 A - Diagonal String | 提出結果 | 提出結果

解答例:answer_5-3-32.py
c1 = input()
c2 = input()
c3 = input()
print(c1[0]+c2[1]+c3[2])
解答例:answer_5-3-33.py
c1 = input()[0]
c2 = input()[1]
c3 = input()[2]
print(c1+c2+c3)

ABC041 A - 添字 | 提出結果

解答例:answer_5-3-34.py
s = input()
i = int(input())
print(s[i-1])

ABC218 A - Weather Forecast | 提出結果

解答例:answer_5-3-35.py
N = int(input())
S = input()
if S[N-1] == "o":
    print("Yes")
else:
    print("No")

ABC244 A - Last Letter | 提出結果 | 提出結果

解答例:answer_5-3-36.py
N = int(input())
S = input()
print(S[N-1])
解答例:answer_5-3-37.py
N = int(input())
S = input()
print(S[-1])

ABC038 A - お茶 | 提出結果

解答例:answer_5-3-38.py
S = input()
if S[-1] == "T":
    print("YES")
else:
    print("NO")

ABC179 A - Plural Form | 提出結果

解答例:answer_5-3-39.py
S = input()
if S[-1] != "s":
    print(S+"s")
else:
    print(S+"es")

ABC060 A - Shiritori | 提出結果

解答例:answer_5-3-40.py
A, B, C = input().split()
if A[-1] == B[0] and B[-1] == C[0]:
    print("YES")
else:
    print("NO")

ABC189 A - Slot | 提出結果

解答例:answer_5-3-41.py
C = input()
if C[0] == C[1] == C[2]:
    print("Won")
else:
    print("Lost")

ABC033 A - 暗証番号 | 提出結果

解答例:answer_5-3-42.py
N = input()
if N[0] == N[1] == N[2] == N[3]:
    print("SAME")
else:
    print("DIFFERENT")

ABC160 A - Coffee | 提出結果

解答例:answer_5-3-43.py
S = input()
if S[2] == S[3] and S[4] == S[5]:
    print("Yes")
else:
    print("No")

ABC079 A - Good Integer | 提出結果

解答例:answer_5-3-44.py
N = input()
if N[0] == N[1] == N[2] or N[1] == N[2] == N[3]:
    print("Yes")
else:
    print("No")

ABC131 A - Security | 提出結果 | 提出結果

解答例:answer_5-3-45.py
S = input()
if S[0] != S[1] and S[1] != S[2] and S[2] != S[3]:
    print("Good")
else:
    print("Bad")
解答例:answer_5-3-46.py
S = input()
if S[0] != S[1] != S[2] != S[3]:
    print("Good")
else:
    print("Bad")

ABC070 A - Palindromic Number | 提出結果

解答例:answer_5-3-47.py
N = input()
if N[0] == N[2]:
    print("Yes")
else:
    print("No")

ABC226 A - Round decimals | 提出結果

解答例:answer_5-3-48.py
a, b = input().split(".")
if int(b[0]) < 5:
    print(int(a))
else:
    print(int(a)+1)

ABC139 A - Tenki | 提出結果

解答例:answer_5-3-49.py
S = input()
T = input()
count = 0
if S[0] == T[0]:
    count += 1
if S[1] == T[1]:
    count += 1
if S[2] == T[2]:
    count += 1
print(count)

ABC375 A - Seats | 提出結果

解答例:answer_5-3-50.py
N = int(input())
S = input()
count = 0
for i in range(1, N-1):
    if S[i-1] == "#" and S[i] == "." and S[i+1] == "#":
        count += 1
print(count)

ABC062 A - Grouping | 提出結果

解答例:answer_5-3-51.py
S = "XACABABAABABA"
x, y = map(int, input().split())
if S[x] == S[y]:
    print("Yes")
else:
    print("No")

ABC025 A - 25個の文字列 | 提出結果

解答例:answer_5-3-52.py
S = input()
N = int(input())-1
print(S[N//5]+S[N % 5])

文字列の探索

文字列の探索はindexメソッドを使用する。探索される文字列.index(探索する文字列)で探索する。探索する文字列が含まれる場合は最小のインデックスが返却され、探索する文字列が含まれない場合はValueErrorが返却される。

サンプルコード:sample_5-3-11.py
x = "abcdef"
print(x.index("c"))
実行結果
2
サンプルコード:sample_5-3-12.py
x = "abcdcc"
print(x.index("c"))
実行結果
2
サンプルコード:sample_5-3-13.py
x = "12345"
print(x.index("3"))
実行結果
2
サンプルコード:sample_5-3-14.py
x = "abc"
print(x.index("z"))
実行結果
ValueError: substring not found

ABC013 A - A | 提出結果 | 提出結果

解答例:answer_5-3-53.py
X = input()
print("ABCDE".index(X)+1)
解答例:answer_5-3-54.py
X = input()
print("0ABCDE".index(X))

ABC151 A - Next Alphabet | 提出結果

解答例:answer_5-3-55.py
C = input()
letters = "abcdefghijklmnopqrstuvwxyz"
print(letters[letters.index(C)+1])

ABC360 A - A Healthy Breakfast | 提出結果

解答例:answer_5-3-56.py
S = input()
if S.index("R") < S.index("M"):
    print("Yes")
else:
    print("No")

ABC322 A - First ABC 2 | 提出結果

解答例:answer_5-3-57.py
N = int(input())
S = input()
if "ABC" in S:
    print(S.index("ABC")+1)
else:
    print(-1)

文字列を前方から検索

文字列を前方から検索する場合はfindメソッドを使用する。検索される文字列.find(検索する文字列)で検索する。検索する文字列が含まれる場合は最小のインデックスが返却され、検索する文字列が含まれない場合は-1が返却される。

サンプルコード:sample_5-3-15.py
x = "abcabc"
print(x.find("b"))
実行結果
1
サンプルコード:sample_5-3-16.py
x = "abcabc"
print(x.find("z"))
実行結果
-1

ABC013 A - A | 提出結果 | 提出結果

解答例:answer_5-3-58.py
X = input()
print("ABCDE".find(X)+1)
解答例:answer_5-3-59.py
X = input()
print("0ABCDE".find(X))

ABC151 A - Next Alphabet | 提出結果

解答例:answer_5-3-60.py
C = input()
letters = "abcdefghijklmnopqrstuvwxyz"
print(letters[letters.find(C)+1])

ABC360 A - A Healthy Breakfast | 提出結果

解答例:answer_5-3-61.py
S = input()
if S.find("R") < S.find("M"):
    print("Yes")
else:
    print("No")

ABC322 A - First ABC 2 | 提出結果

解答例:answer_5-3-62.py
N = int(input())
S = input()
if "ABC" in S:
    print(S.find("ABC")+1)
else:
    print(-1)

文字列を後方から検索

文字列を後方から検索する場合はrfindメソッドを使用する。検索される文字列.rfind(検索する文字列)で検索する。検索する文字列が含まれる場合は最大のインデックスが返却され、検索する文字列が含まれない場合は-1が返却される。

サンプルコード:sample_5-3-17.py
x = "abcabc"
print(x.rfind("b"))
実行結果
4
サンプルコード:sample_5-3-18.py
x = "abcabc"
print(x.rfind("z"))
実行結果
-1

ABC276 A - Rightmost | 提出結果

解答例:answer_5-3-63.py
S = input()
idx = S.rfind("a")
if idx != -1:
    print(idx+1)
else:
    print(-1)

ABC299 A - Treasure Chest | 提出結果

解答例:answer_5-3-64.py
N = int(input())
S = input()
if S.find("|") < S.find("*") < S.rfind("|"):
    print("in")
else:
    print("out")

文字列のカウント

文字列のカウントはcountメソッドを使用する。カウントされる文字列.count(カウントする文字列)でカウント数が返却される。

サンプルコード:sample_5-3-19.py
x = "abbccc"
print(x.count("c"))
実行結果
3
サンプルコード:sample_5-3-20.py
x = "abbccc"
print(x.count("d"))
実行結果
0
サンプルコード:sample_5-3-21.py
x = "123435"
print(x.count("3"))
実行結果
2

ABC081 A - Placing Marbles | 提出結果

解答例:answer_5-3-65.py
s = input()
print(s.count("1"))

ABC279 A - wwwvvvvvv | 提出結果

解答例:answer_5-3-66.py
S = input()
print(S.count("v")+2*S.count("w"))

ABC394 A - 22222 | 提出結果

解答例:answer_5-3-67.py
S = input()
print("2"*S.count("2"))

ABC101 A - Eating Symbols Easy | 提出結果

解答例:answer_5-3-68.py
S = input()
print(S.count("+")-S.count("-"))

ABC095 A - Something on It | 提出結果

解答例:answer_5-3-69.py
S = input()
print(700+100*S.count("o"))

ABC382 A - Daily Cookie | 提出結果 | 提出結果

解答例:answer_5-3-70.py
N, D = map(int, input().split())
S = input()
print(S.count(".")+D)
解答例:answer_5-3-71.py
N, D = map(int, input().split())
S = input()
print(N-S.count("@")+D)

ABC162 A - Lucky 7 | 提出結果

解答例:answer_5-3-72.py
N = input()
if N.count("7") > 0:
    print("Yes")
else:
    print("No")

ABC377 A - Rearranging ABC | 提出結果

解答例:answer_5-3-73.py
S = input()
if S.count("A") == 1 and S.count("B") == 1 and S.count("C") == 1:
    print("Yes")
else:
    print("No")

ABC380 A - 123233 | 提出結果

解答例:answer_5-3-74.py
N = input()
if N.count("1") == 1 and N.count("2") == 2 and N.count("3") == 3:
    print("Yes")
else:
    print("No")

ABC175 A - Rainy Season | 提出結果

解答例:answer_5-3-75.py
S = input()
if S.count("R") != 2:
    print(S.count("R"))
elif S[1] == "R":
    print(2)
else:
    print(1)

ABC298 A - Job Interview | 提出結果

解答例:answer_5-3-76.py
N = int(input())
S = input()
if S.count("o") >= 1 and S.count("x") == 0:
    print("Yes")
else:
    print("No")

ABC301 A - Overall Winner | 提出結果

解答例:answer_5-3-77.py
N = int(input())
S = input()
T = S.count("T")
A = S.count("A")
if T > A:
    print("T")
elif T < A:
    print("A")
else:
    if S[-1] == "A":
        print("T")
    else:
        print("A")

ABC345 A - Leftrightarrow | 提出結果

解答例:answer_5-3-78.py
S = input()
if S[0] == "<" and S.count("<") == 1 and S[-1] == ">" and S.count(">") == 1:
    print("Yes")
else:
    print("No")

ABC280 A - Pawn on a Grid | 提出結果

解答例:answer_5-3-79.py
H, W = map(int, input().split())
S = [input() for i in range(H)]
ans = 0
for s in S:
    ans += s.count("#")
print(ans)

文字列のスライス

文字列のスライスは文字列[開始のインデックス:終了のインデックス:ステップ数]となる。

サンプルコード:sample_5-3-22.py
x = "012345"
print(x[1:4])
実行結果
123
サンプルコード:sample_5-3-23.py
x = "012345"
print(x[1:4:2])
実行結果
13
サンプルコード:sample_5-3-24.py
x = "012345"
print(x[:3])
実行結果
012
サンプルコード:sample_5-3-25.py
x = "012345"
print(x[3:])
実行結果
34
サンプルコード:sample_5-3-26.py
x = "012345"
print(x[:-1])
実行結果
01234
サンプルコード:sample_5-3-27.py
x = "012345"
print(x[-1:])
実行結果
5
サンプルコード:sample_5-3-28.py
x = "012345"
print(x[::2])
実行結果
024
サンプルコード:sample_5-3-29.py
x = "012345"
print(x[1::2])
実行結果
135

ABC254 A - Last Two Digits | 提出結果

解答例:answer_5-3-80.py
N = input()
print(N[1:])

ABC314 A - 3.14 | 提出結果

解答例:answer_5-3-81.py
N = int(input())
pi = "3.1415926535897932384626433832795028841971693993751"\
     "058209749445923078164062862089986280348253421170679"
print(pi[:N+2])

ABC085 A - Already 2018 | 提出結果

解答例:answer_5-3-82.py
S = input()
print("2018"+S[4:])

ABC247 A - Move Right | 提出結果

解答例:answer_5-3-83.py
S = input()
print("0"+S[:3])

ABC282 A - Generalized ABC | 提出結果

解答例:answer_5-3-84.py
K = int(input())
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(letters[:K])

ABC264 A - "atcoder".substr() | 提出結果

解答例:answer_5-3-85.py
L, R = map(int, input().split())
print("atcoder"[L-1:R])

ABC335 A - 202<s>3</s> | 提出結果

解答例:answer_5-3-86.py
S = input()
print(S[:-1]+"4")

ABC197 A - Rotate | 提出結果

解答例:answer_5-3-87.py
S = input()
print(S[1:]+S[0])

ABC236 A - chukodai | 提出結果

解答例:answer_5-3-88.py
S = input()
a, b = map(int, input().split())
print(S[:a-1]+S[b-1]+S[a:b-1]+S[a-1]+S[b:])

ABC339 A - TLD | 提出結果

解答例:answer_5-3-89.py
S = input()
dot = S.rfind(".")
print(S[dot+1:])

ABC251 A - Six Characters | 提出結果

解答例:answer_5-3-90.py
S = input()
print((S*6)[:6])

ABC348 A - Penalty Kick | 提出結果

解答例:answer_5-3-91.py
N = int(input())
S = "oox"*34
print(S[:N])

ABC167 A - Registration | 提出結果

解答例:answer_5-3-92.py
S = input()
T = input()
if S == T[:-1]:
    print("Yes")
else:
    print("No")

ABC374 A - Takahashi san 2 | 提出結果

解答例:answer_5-3-93.py
S = input()
if S[-3:] == "san":
    print("Yes")
else:
    print("No")

ABC224 A - Tires | 提出結果

解答例:answer_5-3-94.py
S = input()
if S[-2:] == "er":
    print("er")
else:
    print("ist")

ABC375 A - Seats | 提出結果

解答例:answer_5-3-95.py
N = int(input())
S = input()
count = 0
for i in range(1, N-1):
    if S[i-1:i+2] == "#.#":
        count += 1
print(count)

ABC072 B - OddString | 提出結果

解答例:answer_5-3-96.py
s = input()
print(s[::2])

文字列の逆順

文字列の逆順は文字列[::-1]となる。

サンプルコード:sample_5-3-30.py
x = "Hello World"
print(x[::-1])
実行結果
dlroW olleH

ABC070 A - Palindromic Number | 提出結果

解答例:answer_5-3-97.py
N = input()
if N == N[::-1]:
    print("Yes")
else:
    print("No")

ABC077 A - Rotation | 提出結果

解答例:answer_5-3-98.py
c1 = input()
c2 = input()
if c1 == c2[::-1]:
    print("YES")
else:
    print("NO")

ABC339 A - TLD | 提出結果

解答例:answer_5-3-99.py
S = input()
ans = ""
for s in S[::-1]:
    if s == ".":
        break
    else:
        ans += s
print(ans[::-1])

文字列の置換

文字列の置換はreplaceメソッドを使用する。文字列.replace("置換前文字列","置換後文字列")で置換する。

サンプルコード:sample_5-3-31.py
x = "abcabcabc"
print(x.replace("b", "p"))
実行結果
apcapcapc

ABC372 A - delete . | 提出結果

解答例:answer_5-3-100.py
S = input()
print(S.replace(".", ""))

ABC289 A - flip | 提出結果

解答例:answer_5-3-101.py
s = input()
print(s.replace("0", "x").replace("1", "0").replace("x", "1"))

ABC111 A - AtCoder Beginner Contest 999 | 提出結果

解答例:answer_5-3-102.py
n = input()
print(n.replace("1", "x").replace("9", "1").replace("x", "9"))

ABC315 A - tcdr | 提出結果

解答例:answer_5-3-103.py
S = input()
print(S.replace("a", "")
      .replace("e", "")
      .replace("i", "")
      .replace("o", "")
      .replace("u", ""))

ABC299 A - Treasure Chest | 提出結果

解答例:answer_5-3-104.py
N = int(input())
S = input()
if S.replace(".", "") == "|*|":
    print("in")
else:
    print("out")

ABC303 A - Similar String | 提出結果

解答例:answer_5-3-105.py
N = int(input())
S = input().replace("1", "l").replace("0", "o")
T = input().replace("1", "l").replace("0", "o")
if S == T:
    print("Yes")
else:
    print("No")

文字列の大文字/小文字変換

文字列の大文字変換はupperメソッド、小文字変換はlowerメソッドを使用する。

サンプルコード:sample_5-3-32.py
x = "Hello World!"
print(x.upper())
実行結果
HELLO WORLD!
サンプルコード:sample_5-3-33.py
x = "Hello World!"
print(x.lower())
実行結果
hello world!

ABC292 A - CAPS LOCK | 提出結果

解答例:answer_5-3-106.py
S = input()
T = S.upper()
print(T)

ABC059 A - Three-letter acronym | 提出結果 | 提出結果

解答例:answer_5-3-107.py
s1, s2, s3 = input().split()
print((s1[0]+s2[0]+s3[0]).upper())
解答例:answer_5-3-108.py
S = input().split()
for s in S:
    print(s[0].upper(), end="")

ABC126 A - Changing a Character | 提出結果

解答例:answer_5-3-109.py
N, K = map(int, input().split())
S = input()
print(S[:K-1]+S[K-1:K].lower()+S[K:])

ABC338 A - Capitalized? | 提出結果

解答例:answer_5-3-110.py
S = input()
if S == S[0].upper()+S[1:].lower():
    print("Yes")
else:
    print("No")

文字列の大文字/小文字判定

文字列の大文字判定はisupperメソッド、小文字判定はislowerメソッドを使用する。

サンプルコード:sample_5-3-34.py
x = "ABC"
print(x.isupper())
実行結果
True
サンプルコード:sample_5-3-35.py
x = "abc"
print(x.islower())
実行結果
True

ABC402 A - CBC | 提出結果

解答例:answer_5-3-111.py
S = input()
ans = ""
for s in S:
    if s.isupper():
        ans += s
print(ans)

ABC291 A - camel Case | 提出結果

解答例:answer_5-3-112.py
S = input()
idx = 1
for s in S:
    if s.isupper():
        break
    else:
        idx += 1
print(idx)

文字列のゼロ埋め

文字列のゼロ埋めはzfillメソッドを使用する。引数では0で埋める桁数を指定する。

サンプルコード:sample_5-3-36.py
x = "12"
print(x.zfill(4))
実行結果
0012
サンプルコード:sample_5-3-37.py
x = "12"
print("ABC"+x.zfill(3))
実行結果
ABC012
サンプルコード:sample_5-3-38.py
x = "5"
print("12:"+x.zfill(2))
実行結果
12:05

ABC222 A - Four Digits | 提出結果

解答例:answer_5-3-113.py
N = input()
print(N.zfill(4))

ABC230 A - AtCoder Quiz 3 | 提出結果

解答例:answer_5-3-114.py
N = int(input())
if N < 42:
    print("AGC"+str(N).zfill(3))
else:
    print("AGC"+str(N+1).zfill(3))

文字列のフォーマット

文字列のフォーマットはフォーマット済み文字列リテラルを使用する。

ゼロ埋め

ゼロ埋めはf"{変数または式:0ゼロ埋めする桁数}"で指定する。

サンプルコード:sample_5-3-39.py
x = 12
print(f"{x:04}")
実行結果
0012
サンプルコード:sample_5-3-40.py
x = 12
print(f"ABC{x:03}")
実行結果
ABC012
サンプルコード:sample_5-3-41.py
x = 5
print(f"12:{x:02}")
実行結果
12:05

ABC222 A - Four Digits | 提出結果

解答例:answer_5-3-115.py
N = int(input())
print(f"{N:04}")

ABC230 A - AtCoder Quiz 3 | 提出結果

解答例:answer_5-3-116.py
N = int(input())
if N < 42:
    print(f"AGC{N:03}")
else:
    print(f"AGC{N+1:03}")

小数点桁数

小数点桁数はf"{変数または式:.小数点桁数f}"で指定する。

サンプルコード:sample_5-3-42.py
x = 1.23456
print(f"{x:.0f}")
print(f"{x:.1f}")
print(f"{x:.2f}")
print(f"{x:.3f}")
print(f"{x:.4f}")
実行結果
1
1.2
1.23
1.235
1.2346

ABC274 A - Batting Average | 提出結果

解答例:answer_5-3-117.py
A, B = map(int, input().split())
print(f"{B/A:.3f}")

進数

進数はf"{変数または式:進数の変換型}"で指定する。進数の変換型は下記の表の通りとなる。

変換 意味
b 2進数
o 8進数
d 10進数
x 16進数小文字
X 16進数大文字
サンプルコード:sample_5-3-43.py
num = 10
print(f"bin(b):{num:b}")
print(f"oct(o):{num:o}")
print(f"dec(d):{num:d}")
print(f"hex(x):{num:x}")
print(f"HEX(X):{num:X}")
実行結果
bin(b):1010
oct(o):12
dec(d):10
hex(x):a
HEX(X):A

ABC271 A - 484558 | 提出結果

解答例:answer_5-3-118.py
N = int(input())
print(f"{N:02X}")

5.4 リスト(list)

キーポイント

  • 要素の参照はリスト[インデックス]となる。
  • 数値の要素に算術演算を使用することができる。
  • 文字列の要素の連結は+演算子を使用する。
  • リストの連結は+演算子を使用する。
  • リストの繰り返しは*演算子を使用する。
  • 要素の探索はindexメソッドを使用する。
  • 要素のカウントはcountメソッドを使用する。
  • 要素の追加はappendメソッドを使用する。
  • 要素の挿入はinsertメソッドを使用する。
  • 要素の取り出しはpopメソッドを使用する。
  • 要素のユニーク化はリストlist型から集合set型に変換することにより、要素がユニークとなる。ただし、要素の順序は保たれない。
  • 要素のスライスはリスト[開始のインデックス:終了のインデックス:ステップ数]となる。

要素の参照

要素の参照はリスト[インデックス]となる。範囲外の参照はIndexErrorが返却される。

サンプルコード:sample_5-4-1.py
x = [1, 2, 3]
print(x[0], x[1], x[2])
実行結果
1 2 3
サンプルコード:sample_5-4-2.py
x = [1, 2, 3]
print(x[-1], x[-2], x[-3])
実行結果
3 2 1
サンプルコード:sample_5-4-3.py
x = ["a", "b", "c"]
print(x[0], x[1], x[2])
実行結果
a b c
サンプルコード:sample_5-4-4.py
x = ["a", "b", "c"]
print(x[-1], x[-2], x[-3])
実行結果
c b a
サンプルコード:sample_5-4-5.py
x = ["a", "b", "c"]
print(x[3])
実行結果
IndexError: list index out of range

ABC255 A - You should output ARC, though this is ABC. | 提出結果

解答例:answer_5-4-1.py
R, C = map(int, input().split())
A = [input().split() for i in range(2)]
print(A[R-1][C-1])

ABC241 A - Digit Machine | 提出結果 | 提出結果

解答例:answer_5-4-2.py
a = list(map(int, input().split()))
print(a[a[a[0]]])
解答例:answer_5-4-3.py
a = list(map(int, input().split()))
idx = 0
for i in range(2):
    idx = a[idx]
print(a[idx])

ABC339 A - TLD | 提出結果

解答例:answer_5-4-4.py
S = input()
print(S.split(".")[-1])

ABC168 A - ∴ (Therefore) | 提出結果

解答例:answer_5-4-5.py
N = input()
book = ["pon", "pon", "hon", "bon", "hon", "hon", "pon", "hon", "pon", "hon"]
print(book[int(N[-1])])

ABC284 A - Sequence of Strings | 提出結果 | 提出結果

解答例:answer_5-4-6.py
N = int(input())
S = [input() for i in range(N)]
for i in range(N):
    print(S[N-i-1])
解答例:answer_5-4-7.py
N = int(input())
S = [input() for i in range(N)]
for i in range(N-1, -1, -1):
    print(S[i])

ABC399 A - Hamming Distance | 提出結果

解答例:answer_5-4-8.py
N = int(input())
S = input()
T = input()
ans = 0
for i in range(N):
    if S[i] != T[i]:
        ans += 1
print(ans)

ABC403 A - Odd Position Sum | 提出結果

解答例:answer_5-4-9.py
N = int(input())
A = list(map(int, input().split()))
ans = 0
for i in range(N):
    if i % 2 == 0:
        ans += A[i]
print(ans)

ABC353 A - Buildings | 提出結果

解答例:answer_5-4-10.py
N = int(input())
H = list(map(int, input().split()))
for i in range(1, N):
    if H[0] < H[i]:
        print(i+1)
        break
else:
    print(-1)

ABC364 A - Glutton Takahashi | 提出結果

解答例:answer_5-4-11.py
N = int(input())
S = [input() for i in range(N)]
for i in range(N-2):
    if S[i] == "sweet" and S[i+1] == "sweet":
        print("No")
        break
else:
    print("Yes")

ABC376 A - Candy Button | 提出結果

解答例:answer_5-4-12.py
N, C = map(int, input().split())
T = list(map(int, input().split()))
count = 1
before = T[0]
for t in T:
    if t-before >= C:
        count += 1
        before = t
print(count)

ABC308 A - New Scheme | 提出結果

解答例:answer_5-4-13.py
S = list(map(int, input().split()))
flag = True
for i in range(7):
    if S[i] <= S[i+1]:
        continue
    else:
        flag = False
for s in S:
    if 100 <= s <= 675 and s % 25 == 0:
        continue
    else:
        flag = False
print("Yes" if flag else "No")

要素の算術演算

  • 数値の要素に算術演算を使用することができる。
サンプルコード:sample_5-4-6.py
x = [1, 2, 3]
print(x[0]+x[1])
実行結果
3
サンプルコード:sample_5-4-7.py
x = [1, 2, 3]
print(x[-1]*x[-2])
実行結果
6

ABC346 A - Adjacent Product | 提出結果

解答例:answer_5-4-14.py
N = int(input())
A = list(map(int, input().split()))
for i in range(N-1):
    print(A[i]*A[i+1], end=" ")

ABC272 A - Integer Sum | 提出結果

解答例:answer_5-4-15.py
N = int(input())
A = list(map(int, input().split()))
total = 0
for i in range(N):
    total += A[i]
print(total)

ABC290 A - Contest Result | 提出結果 | 提出結果

解答例:answer_5-4-16.py
N, M = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
total = 0
for b in B:
    total += A[b-1]
print(total)
解答例:answer_5-4-17.py
N, M = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
total = 0
for i in range(M):
    total += A[B[i]-1]
print(total)

ABC297 A - Double Click | 提出結果

解答例:answer_5-4-18.py
N, D = map(int, input().split())
T = list(map(int, input().split()))
for i in range(N-1):
    if T[i+1]-T[i] <= D:
        print(T[i+1])
        break
else:
    print(-1)

ABC378 A - Pairing | 提出結果

解答例:answer_5-4-19.py
A = list(map(int, input().split()))
color = [0, 0, 0, 0]
for a in A:
    color[a-1] += 1
count = 0
for num in color:
    if num == 4:
        count += 2
    elif num in [2, 3]:
        count += 1
print(count)

要素の連結

  • 文字列の要素の連結は+演算子を使用する。
サンプルコード:sample_5-4-8.py
x = ["Hello", "World", "!"]
print(x[0]+x[1])
実行結果
HelloWorld
サンプルコード:sample_5-4-9.py
x = ["Hello", "World", "!"]
print(x[0]+x[-1])
実行結果
Hello!

ABC344 A - Spoiler | 提出結果

解答例:answer_5-4-20.py
S = input().split("|")
print(S[0]+S[2])

リストの連結

  • リストの連結は+演算子を使用する。
サンプルコード:sample_5-4-10.py
x = ["Hello"]
y = ["World"]
print(x+y)
実行結果
['Hello', 'World']
サンプルコード:sample_5-4-11.py
x = [3, 4]
y = [1, 2, 3]
print(x+y)
実行結果
[3, 4, 1, 2, 3]

リストの繰り返し

  • リストの繰り返しは*演算子を使用する。
サンプルコード:sample_5-4-12.py
x = ["Hello", "World"]
print(x*2)
実行結果
['Hello', 'World', 'Hello', 'World']
サンプルコード:sample_5-4-13.py
x = [1, 2, 3]
print(x*3)
実行結果
[1, 2, 3, 1, 2, 3, 1, 2, 3]

要素の探索

要素の探索はindexメソッドを使用する。探索されるリスト.index(探索する要素)で探索する。探索する要素が含まれる場合は最小のインデックスが返却され、探索する要素が含まれない場合はValueErrorが返却される。

サンプルコード:sample_5-4-14.py
x = [1, 2, 3, 4, 5]
print(x.index(3))
実行結果
2
サンプルコード:sample_5-4-15.py
x = ["a", "b", "c", "d", "e", "f"]
print(x.index("c"))
実行結果
2
サンプルコード:sample_5-4-16.py
x = ["a", "b", "c", "d", "c", "c"]
print(x.index("c"))
実行結果
2
サンプルコード:sample_5-4-17.py
x = ["a", "b", "c"]
print(x.index("z"))
実行結果
ValueError: 'z' is not in list

ABC013 A - A | 提出結果 | 提出結果

解答例:answer_5-4-21.py
X = input()
print(["A", "B", "C", "D", "E"].index(X)+1)
解答例:answer_5-4-22.py
X = input()
print(["0", "A", "B", "C", "D", "E"].index(X))

ABC170 A - Five Variables | 提出結果 | 提出結果

解答例:answer_5-4-23.py
x = list(map(int, input().split()))
print(x.index(0)+1)
解答例:answer_5-4-24.py
x = input().split()
print(x.index("0")+1)

ABC277 A - ^{-1} | 提出結果 | 提出結果

解答例:answer_5-4-25.py
N, X = map(int, input().split())
P = list(map(int, input().split()))
print(P.index(X)+1)
解答例:answer_5-4-26.py
N, X = input().split()
P = input().split()
print(P.index(X)+1)

ABC300 A - N-choice question | 提出結果

解答例:answer_5-4-27.py
N, A, B = map(int, input().split())
C = list(map(int, input().split()))
print(C.index(A+B)+1)

ABC146 A - Can't Wait for Holiday | 提出結果 | 提出結果

解答例:answer_5-4-28.py
S = input()
week = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]
print(7-week.index(S))
解答例:answer_5-4-29.py
S = input()
week = ["0", "SAT", "FRI", "THU", "WED", "TUE", "MON", "SUN"]
print(week.index(S))

ABC267 A - Saturday | 提出結果 | 提出結果

解答例:answer_5-4-30.py
S = input()
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
print(5-week.index(S))
解答例:answer_5-4-31.py
S = input()
week = ["0", "Friday", "Thursday", "Wednesday", "Tuesday", "Monday"]
print(week.index(S))

ABC141 A - Weather Prediction | 提出結果 | 提出結果

解答例:answer_5-4-32.py
S = input()
weather = ["Sunny", "Cloudy", "Rainy", "Sunny"]
print(weather[(weather.index(S)+1)])
解答例:answer_5-4-33.py
S = input()
weather = ["Sunny", "Cloudy", "Rainy"]
print(weather[(weather.index(S)+1) % 3])

ABC275 A - Find Takahashi | 提出結果

解答例:answer_5-4-34.py
N = int(input())
H = list(map(int, input().split()))
bridge = 0
for h in H:
    if h > bridge:
        bridge = h
print(H.index(bridge)+1)

ABC391 A - Lucky Direction | 提出結果

解答例:answer_5-4-35.py
D = input()
d = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
print(d[d.index(D)-4])

要素のカウント

要素のカウントはcountメソッドを使用する。カウントされるリスト.count(カウントする要素)でカウント数が返却される。

サンプルコード:sample_5-4-18.py
x = [1, 2, 3, 4, 3, 5]
print(x.count(3))
実行結果
2
サンプルコード:sample_5-4-19.py
x = ["a", "b", "b", "c", "c", "c"]
print(x.count("c"))
実行結果
3
サンプルコード:sample_5-4-20.py
x = ["a", "b", "b", "c", "c", "c"]
print(x.count("d"))
実行結果
0

ABC359 A - Count Takahashi | 提出結果

解答例:answer_5-4-36.py
N = int(input())
S = [input() for i in range(N)]
print(S.count("Takahashi"))

ABC042 A - 和風いろはちゃんイージー | 提出結果 | 提出結果

解答例:answer_5-4-37.py
ABC = list(map(int, input().split()))
if ABC.count(5) == 2 and ABC.count(7) == 1:
    print("YES")
else:
    print("NO")
解答例:answer_5-4-38.py
ABC = input().split()
if ABC.count("5") == 2 and ABC.count("7") == 1:
    print("YES")
else:
    print("NO")

ABC287 A - Majority | 提出結果

解答例:answer_5-4-39.py
N = int(input())
S = [input() for i in range(N)]
if S.count("For") > N/2:
    print("Yes")
else:
    print("No")

要素の追加

要素の追加はappendメソッドを使用する。リスト.append(要素)でリストの最後に要素が追加される。

サンプルコード:sample_5-4-21.py
x = ["a", "b", "c"]
x.append("d")
print(x)
実行結果
['a', 'b', 'c', 'd']
サンプルコード:sample_5-4-22.py
x = [0, 1, 2]
x.append(3)
print(x)
実行結果
[0, 1, 2, 3]

要素の挿入

要素の挿入はinsertメソッドを使用する。リスト.insert(挿入先のインデックス, 要素)でリストに要素が挿入される。

サンプルコード:sample_5-4-23.py
x = ["a", "b", "c"]
x.insert(1, "z")
print(x)
実行結果
['a', 'z', 'b', 'c']

ABC361 A - Insert | 提出結果

解答例:answer_5-4-40.py
N, K, X = map(int, input().split())
A = list(map(int, input().split()))
A.insert(K, X)
print(*A)

要素の取り出し

要素の取り出しはpopメソッドを使用する。リスト.pop(インデックス)でインデックスの要素が取り出される。インデックスを指定しない場合リスト.pop()、リストの最後の要素が取り出される。

サンプルコード:sample_5-4-24.py
x = ["a", "b", "c"]
print(x.pop(0))
print(x)
実行結果
a
['b', 'c']
サンプルコード:sample_5-4-25.py
x = [1, 2, 3]
print(x.pop(1))
print(x)
実行結果
2
[1, 3]
サンプルコード:sample_5-4-26.py
x = [1, 2, 3]
print(x.pop())
print(x)
実行結果
3
[1, 2]
サンプルコード:sample_5-4-27.py
x = [1, 2, 3]
print(x.pop(3))
print(x)
実行結果
IndexError: pop index out of range
サンプルコード:sample_5-4-28.py
x = []
print(x.pop())
実行結果
IndexError: pop from empty list

ABC278 A - Shift | 提出結果

解答例:answer_5-4-41.py
N, K = map(int, input().split())
A = list(map(int, input().split()))
for i in range(K):
    A.pop(0)
    A.append(0)
print(*A)

要素のユニーク化

要素のユニーク化はリストlist型から集合set型に変換することにより、要素がユニークとなる。ただし、要素の順序は保たれない。また、集合set型からリストlist型に変換することもできる。

サンプルコード:sample_5-4-29.py
x = [1, 2, 3, 2, 1, 3]
print(list(set(x)))
実行結果
[1, 2, 3]
サンプルコード:sample_5-4-30.py
x = ["b", "a", "c", "a", "b"]
print(list(set(x)))
実行結果
['b', 'c', 'a']

要素のスライス

要素のスライスはリスト[開始のインデックス:終了のインデックス:ステップ数]となる。

サンプルコード:sample_5-4-31.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[1:4])
実行結果
['1', '2', '3']
サンプルコード:sample_5-4-32.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[1:4:2])
実行結果
['1', '3']
サンプルコード:sample_5-4-33.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[:3])
実行結果
['0', '1', '2']
サンプルコード:sample_5-4-34.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[3:])
実行結果
['3', '4', '5']
サンプルコード:sample_5-4-35.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[:-1])
実行結果
['0', '1', '2', '3', '4']
サンプルコード:sample_5-4-36.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[-1:])
実行結果
['5']
サンプルコード:sample_5-4-37.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[::2])
実行結果
['0', '2', '4']
サンプルコード:sample_5-4-38.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[1::2])
実行結果
['1', '3', '5']
サンプルコード:sample_5-4-39.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[::-1])
実行結果
['5', '4', '3', '2', '1', '0']
サンプルコード:sample_5-4-40.py
x = ["0", "1", "2", "3", "4", "5"]
print(x[::-2])
実行結果
['5', '3', '1']

ABC284 A - Sequence of Strings | 提出結果

解答例:answer_5-4-42.py
N = int(input())
S = [input() for i in range(N)]
print(*S[::-1], sep="\n")

ABC286 A - Range Swap | 提出結果 | 提出結果

解答例:answer_5-4-43.py
N, P, Q, R, S = map(int, input().split())
A = list(map(int, input().split()))
A[P-1:Q], A[R-1:S] = A[R-1:S], A[P-1:Q]
print(*A)
解答例:answer_5-4-44.py
N, P, Q, R, S = map(int, input().split())
A = input().split()
A[P-1:Q], A[R-1:S] = A[R-1:S], A[P-1:Q]
print(*A)

ABC356 A - Subsegment Reverse | 提出結果

解答例:answer_5-4-45.py
N, L, R = map(int, input().split())
A = list(range(1, N+1))
A[L-1:R] = A[L-1:R][::-1]
print(*A)

ABC368 A - Cut | 提出結果

解答例:answer_5-4-46.py
N, K = map(int, input().split())
A = list(map(int, input().split()))
print(*A[-K:]+A[:N-K])

ABC304 A - First Player | 提出結果

解答例:answer_5-4-47.py
N = int(input())
S = []
A = []
for i in range(N):
    s, a = input().split()
    S.append(s)
    A.append(int(a))
idx = A.index(min(A))
print(*S[idx:]+S[:idx], sep="\n")

5.5 集合(set)

キーポイント

  • 集合への変換はset(データ)で集合に変換される。
  • 集合の和は|を使用する。
  • 集合の差は-を使用する。
  • 集合の積は&を使用する。
  • 集合の対称差は^を使用する。
  • 部分集合は不等式を使用する。
  • 要素の追加はaddメソッドを使用する。
  • 要素の取り出しはpopメソッドを使用する。
  • 要素の取り除きはdiscardメソッドを使用する。

集合への変換

集合への変換はset(データ)で集合に変換される。

サンプルコード:sample_5-5-1.py
x = "abcabc"
print(set(x))
実行結果
{'b', 'c', 'a'}
サンプルコード:sample_5-5-2.py
x = ["a", "b", "c", "a", "b", "c"]
print(set(x))
実行結果
{'c', 'a', 'b'}

集合の和

集合の和は|を使用する。

サンプルコード:sample_5-5-3.py
print({"a", "b", "c"} | {"c", "d", "e"})
実行結果
{'a', 'b', 'd', 'e', 'c'}

集合の差

集合の差は-を使用する。

サンプルコード:sample_5-5-4.py
print({"a", "b", "c"} - {"c", "d", "e"})
実行結果
{'a', 'b'}

ABC148 A - Round One | 提出結果

解答例:answer_5-5-1.py
U = {1, 2, 3}
AB = set(int(input()) for i in range(2))
print(list(U-AB)[0])

ABC248 A - Lacked Number | 提出結果 | 提出結果

解答例:answer_5-5-2.py
U = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
S = set(input())
print(list(U-S)[0])
解答例:answer_5-5-3.py
U = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
S = set(map(int, input()))
print(list(U-S)[0])

集合の積

集合の積は&を使用する。

サンプルコード:sample_5-5-5.py
print({"a", "b", "c"} & {"c", "d", "e"})
実行結果
{'c'}

ABC295 A - Probably English | 提出結果

解答例:answer_5-5-4.py
N = int(input())
W = set(input().split())
S = {"and", "not", "that", "the", "you"}
if S & W:
    print("Yes")
else:
    print("No")

集合の対称差

集合の対称差は^を使用する。

サンプルコード:sample_5-5-6.py
print({"a", "b", "c"} ^ {"c", "d", "e"})
実行結果
{'a', 'b', 'e', 'd'}

部分集合

部分集合は不等式を使用する。

サンプルコード:sample_5-5-7.py
print({"a", "b"} <= {"a", "b", "c"})
実行結果
True
サンプルコード:sample_5-5-8.py
print({"a", "z"} <= {"a", "b", "c"})
実行結果
False
サンプルコード:sample_5-5-9.py
print({"a", "b", "c"} >= {"a", "b"})
実行結果
True
サンプルコード:sample_5-5-10.py
print({"a", "b", "c"} >= {"a", "z"})
実行結果
False

ABC062 A - Grouping | 提出結果 | 提出結果

解答例:answer_5-5-5.py
x, y = map(int, input().split())
group1 = {1, 3, 5, 7, 8, 10, 12}
group2 = {4, 6, 9, 11}
if {x, y} <= group1 or {x, y} <= group2:
    print("Yes")
else:
    print("No")
解答例:answer_5-5-6.py
x, y = input().split()
group1 = {"1", "3", "5", "7", "8", "10", "12"}
group2 = {"4", "6", "9", "11"}
if {x, y} <= group1 or {x, y} <= group2:
    print("Yes")
else:
    print("No")

要素の追加

要素の追加はaddメソッドを使用する。

サンプルコード:sample_5-5-11.py
x = set()
x.add("a")
print(x)
実行結果
{'a'}
サンプルコード:sample_5-5-12.py
x = set()
x.add(1)
print(x)
実行結果
{1}

要素の取り出し

要素の取り出しはpopメソッドを使用する。

サンプルコード:sample_5-5-13.py
x = {"a"}
print(x.pop())
実行結果
a

ABC148 A - Round One | 提出結果

解答例:answer_5-5-7.py
U = {1, 2, 3}
AB = set(int(input()) for i in range(2))
print((U-AB).pop())

ABC248 A - Lacked Number | 提出結果 | 提出結果

解答例:answer_5-5-8.py
U = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
S = set(input())
print((U-S).pop())
解答例:answer_5-5-9.py
U = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
S = set(map(int, input()))
print((U-S).pop())

要素の取り除き

要素の取り除きはdiscardメソッドを使用する。

サンプルコード:sample_5-5-14.py
x = {"a", "b", "c"}
x.discard("a")
print(x)
実行結果
{'c', 'b'}
サンプルコード:sample_5-5-15.py
x = {"a", "b", "c"}
x.discard("z")
print(x)
実行結果
{'b', 'a', 'c'}

ABC355 A - Who Ate the Cake? | 提出結果

解答例:answer_5-5-10.py
A, B = map(int, input().split())
s = {1, 2, 3}
s.discard(A)
s.discard(B)
if A == B:
    print(-1)
else:
    print(s.pop())

5.6 辞書(dict)

キーポイント

  • 値の参照は辞書[キー]となる。

値の参照

値の参照は辞書[キー]となる。

サンプルコード:sample_5-6-1.py
x = {"a": 1, "b": 2, "c": 3}
print(x["a"])
実行結果
1
サンプルコード:sample_5-6-2.py
x = {1: "a", 2: "b", 3: "c"}
print(x[2])
実行結果
b

ABC013 A - A | 提出結果

解答例:answer_5-6-1.py
X = input()
alphabet = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}
print(alphabet[X])

ABC141 A - Weather Prediction | 提出結果

解答例:answer_5-6-2.py
S = input()
weather = {"Sunny": "Cloudy", "Cloudy": "Rainy", "Rainy": "Sunny"}
print(weather[S])

ABC391 A - Lucky Direction | 提出結果

解答例:answer_5-6-3.py
D = input()
d = {"N": "S", "NE": "SW", "E": "W", "SE": "NW",
     "S": "N", "SW": "NE", "W": "E", "NW": "SE"}
print(d[D])

ABC146 A - Can't Wait for Holiday | 提出結果

解答例:answer_5-6-4.py
S = input()
week = {"SUN": 7, "MON": 6, "TUE": 5, "WED": 4, "THU": 3, "FRI": 2, "SAT": 1}
print(week[S])

ABC267 A - Saturday | 提出結果

解答例:answer_5-6-5.py
S = input()
week = {"Monday": 5, "Tuesday": 4, "Wednesday": 3, "Thursday": 2, "Friday": 1}
print(week[S])

ABC319 A - Legendary Players | 提出結果

解答例:answer_5-6-6.py
rate = {
    "tourist": 3858,
    "ksun48": 3679,
    "Benq": 3658,
    "Um_nik": 3648,
    "apiad": 3638,
    "Stonefeang": 3630,
    "ecnerwala": 3613,
    "mnbvmar": 3555,
    "newbiedmy": 3516,
    "semiexp": 3481
}
S = input()
print(rate[S])

ABC168 A - ∴ (Therefore) | 提出結果

解答例:answer_5-6-7.py
N = input()
book = {"0": "pon", "1": "pon", "2": "hon", "3": "bon", "4": "hon",
        "5": "hon", "6": "pon", "7": "hon", "8": "pon", "9": "hon"}
print(book[N[-1]])

第6章 組み込み関数

第6章では組み込み関数について説明します。

6.1 長さ(len)

キーポイント

  • 文字列とリストの長さを得る場合、len関数を使用する。

文字列の長さ

文字列の長さを得る場合、len(文字列)となる。

サンプルコード:sample_6-1-1.py
x = "Hello"
print(len(x))
実行結果
5

ABC015 A - 高橋くんの研修 | 提出結果

解答例:answer_6-1-1.py
A = input()
B = input()
if len(A) > len(B):
    print(A)
else:
    print(B)

ABC411 A - Required Length | 提出結果

解答例:answer_6-1-2.py
P = input()
L = int(input())
if len(P) >= L:
    print("Yes")
else:
    print("No")

ABC266 A - Middle Letter | 提出結果

解答例:answer_6-1-3.py
S = input()
print(S[len(S)//2])

ABC222 A - Four Digits | 提出結果

解答例:answer_6-1-4.py
N = input()
print("0"*(4-len(N))+N)

ABC033 A - 暗証番号 | 提出結果

解答例:answer_6-1-5.py
N = input()
if len(set(N)) == 1:
    print("SAME")
else:
    print("DIFFERENT")

ABC189 A - Slot | 提出結果

解答例:answer_6-1-6.py
C = input()
if len(set(C)) == 1:
    print("Won")
else:
    print("Lost")

ABC093 A - abc of ABC | 提出結果

解答例:answer_6-1-7.py
S = input()
if len(set(S)) == 3:
    print("Yes")
else:
    print("No")

ABC158 A - Station and Bus | 提出結果

解答例:answer_6-1-8.py
S = input()
if len(set(S)) != 1:
    print("Yes")
else:
    print("No")

ABC225 A - Distinct Strings | 提出結果

解答例:answer_6-1-9.py
S = input()
kind = len(set(S))
if kind == 1:
    print(1)
elif kind == 2:
    print(3)
else:
    print(6)

ABC373 A - September | 提出結果

解答例:answer_6-1-10.py
S = [input() for _ in range(12)]
count = 0
for i in range(12):
    if len(S[i]) == i+1:
        count += 1
print(count)

ABC293 A - Swap Odd and Even | 提出結果

解答例:answer_6-1-11.py
S = input()
for i in range(0, len(S), 2):
    print(S[i+1]+S[i], end="")

ABC345 A - Leftrightarrow | 提出結果

解答例:answer_6-1-12.py
S = input()
flag = True
if S[0] != "<" or S[-1] != ">":
    flag = False
for i in range(1, len(S)-1):
    if S[i] != "=":
        flag = False
if flag:
    print("Yes")
else:
    print("No")

ABC342 A - Yay! | 提出結果

解答例:answer_6-1-13.py
S = input()
if S[0] == S[1]:
    majority = S[0]
else:
    majority = S[2]
for i in range(len(S)):
    if S[i] != majority:
        print(i+1)
        break

リストの長さ

リストの長さを得る場合、len(リスト)となる。

サンプルコード:sample_6-1-2.py
x = ["a", "b", "c", "a"]
print(len(x))
実行結果
4
サンプルコード:sample_6-1-3.py
x = [0, 1, 2]
print(len(x))
実行結果
3

ABC046 A - AtCoDeerくんとペンキ | 提出結果 | 提出結果

解答例:answer_6-1-14.py
abc = input().split()
print(len(set(abc)))
解答例:answer_6-1-15.py
abc = list(map(int, input().split()))
print(len(set(abc)))

ABC268 A - Five Integers | 提出結果 | 提出結果

解答例:answer_6-1-16.py
ABCDE = input().split()
print(len(set(ABCDE)))
解答例:answer_6-1-17.py
ABCDE = list(map(int, input().split()))
print(len(set(ABCDE)))

ABC324 A - Same | 提出結果

解答例:answer_6-1-18.py
N = int(input())
A = list(map(int, input().split()))
if len(set(A)) == 1:
    print("Yes")
else:
    print("No")

ABC155 A - Poor | 提出結果

解答例:answer_6-1-19.py
ABC = input().split()
if len(set(ABC)) == 2:
    print("Yes")
else:
    print("No")

ABC132 A - Fifty-Fifty | 提出結果

解答例:answer_6-1-20.py
S = input()
c = list(set(S))
if len(c) == 2 and S.count(c[0]) == S.count(c[1]) == 2:
    print("Yes")
else:
    print("No")

6.2 ソート(sorted)

キーポイント

  • ソートをする場合、sorted関数を使用する。
  • ソートは昇順で行われる。
  • ソートを降順にする場合、sorted(データ)[::-1]となる。

昇順

ソートをする場合、sorted関数を使用する。ソートは昇順で行われる。

サンプルコード:sample_6-2-1.py
x = [2, 1, 3]
print(sorted(x))
実行結果
[1, 2, 3]

ABC019 A - 高橋くんと年齢 | 提出結果

解答例:answer_6-2-1.py
abc = map(int, input().split())
print(sorted(abc)[1])

ABC066 A - ringring | 提出結果

解答例:answer_6-2-2.py
a, b, c = sorted(map(int, input().split()))
print(a+b)

ABC207 A - Repression | 提出結果

解答例:answer_6-2-3.py
x, y, z = sorted(map(int, input().split()))
print(y+z)

ABC103 A - Task Scheduling Problem | 提出結果 | 提出結果

解答例:answer_6-2-4.py
A1, A2, A3 = sorted(map(int, input().split()))
print(A3-A1)
解答例:answer_6-2-5.py
A = sorted(map(int, input().split()))
print(A[-1]-A[0])

ABC110 A - Maximize the Formula | 提出結果

解答例:answer_6-2-6.py
A, B, C = sorted(input().split())
print(int(C+B)+int(A))

ABC201 A - Tiny Arithmetic Sequence | 提出結果 | 提出結果

解答例:answer_6-2-7.py
A1, A2, A3 = sorted(map(int, input().split()))
if A3-A2 == A2-A1:
    print("Yes")
else:
    print("No")
解答例:answer_6-2-8.py
A = sorted(map(int, input().split()))
if A[2]-A[1] == A[1]-A[0]:
    print("Yes")
else:
    print("No")

ABC392 A - Shuffled Equation | 提出結果

解答例:answer_6-2-9.py
a, b, c = sorted(map(int, input().split()))
if a*b == c:
    print("Yes")
else:
    print("No")

ABC047 A - キャンディーと2人の子供 | 提出結果

解答例:answer_6-2-10.py
a, b, c = sorted(map(int, input().split()))
if a+b == c:
    print("Yes")
else:
    print("No")

ABC385 A - Equally | 提出結果

解答例:answer_6-2-11.py
A, B, C = sorted(map(int, input().split()))
if A == B == C or A+B == C:
    print("Yes")
else:
    print("No")

ABC377 A - Rearranging ABC | 提出結果

解答例:answer_6-2-12.py
S = input()
if sorted(S) == list("ABC"):
    print("Yes")
else:
    print("No")

ABC380 A - 123233 | 提出結果

解答例:answer_6-2-13.py
N = input()
if sorted(N) == list("122333"):
    print("Yes")
else:
    print("No")

ABC395 A - Strictly Increasing? | 提出結果

解答例:answer_6-2-14.py
N = int(input())
A = list(map(int, input().split()))
if A == sorted(set(A)):
    print("Yes")
else:
    print("No")

ABC263 A - Full House | 提出結果 | 提出結果

解答例:answer_6-2-15.py
A, B, C, D, E = sorted(input().split())
if (A == B == C and D == E) or (A == B and C == D == E):
    print("Yes")
else:
    print("No")
解答例:answer_6-2-16.py
A, B, C, D, E = sorted(map(int, input().split()))
if (A == B == C and D == E) or (A == B and C == D == E):
    print("Yes")
else:
    print("No")

ABC260 A - A Unique Letter | 提出結果

解答例:answer_6-2-17.py
a, b, c = sorted(input())
if a != b:
    print(a)
elif b != c:
    print(c)
else:
    print(-1)

ABC342 A - Yay! | 提出結果

解答例:answer_6-2-18.py
S = input()
d = sorted(S)
if d[0] != d[1]:
    print(S.index(d[0])+1)
else:
    print(S.index(d[-1])+1)

降順

ソートを降順にする場合、sorted(データ)[::-1]となる。

サンプルコード:sample_6-2-2.py
x = [2, 1, 3]
print(sorted(x)[::-1])
実行結果
[3, 2, 1]

ABC207 A - Repression | 提出結果

解答例:answer_6-2-19.py
x, y, z = sorted(map(int, input().split()))[::-1]
print(x+y)

ABC110 A - Maximize the Formula | 提出結果

解答例:answer_6-2-20.py
A, B, C = sorted(input().split())[::-1]
print(int(A+B)+int(C))

ABC018 A - 豆まき | 提出結果

解答例:answer_6-2-21.py
ABC = [int(input()) for i in range(3)]
sorted_ABC = sorted(ABC)[::-1]
for idx in ABC:
    print(sorted_ABC.index(idx)+1)

6.3 最大値(max)

キーポイント

  • 最大値を得る場合、max関数を使用する。

整数の場合、max(整数A, 整数B, 整数C)となる。

サンプルコード:sample_6-3-1.py
print(max(1, 2, 3))
実行結果
3

変数の場合、max(変数A, 変数B, 変数C)となる。

サンプルコード:sample_6-3-2.py
x = 1
y = 2
z = 3
print(max(x, y, z))
実行結果
3

リストの場合、max(リスト)となる。

サンプルコード:sample_6-3-3.py
x = [1, 2, 3]
print(max(x))
実行結果
3

ABC002 A - 正直者 | 提出結果

解答例:answer_6-3-1.py
X, Y = map(int, input().split())
print(max(X, Y))

ABC098 A - Add Sub Mul | 提出結果

解答例:answer_6-3-2.py
A, B = map(int, input().split())
print(max(A+B, A-B, A*B))

ABC137 A - +-x | 提出結果

解答例:answer_6-3-3.py
A, B = map(int, input().split())
print(max(A+B, A-B, A*B))

ABC052 A - Two Rectangles | 提出結果

解答例:answer_6-3-4.py
A, B, C, D = map(int, input().split())
print(max(A*B, C*D))

ABC037 A - 饅頭 | 提出結果

解答例:answer_6-3-5.py
A, B, C = map(int, input().split())
print(max(C//A, C//B))

ABC207 A - Repression | 提出結果

解答例:answer_6-3-6.py
A, B, C = map(int, input().split())
print(max(A+B, B+C, C+A))

ABC124 A - Buttons | 提出結果

解答例:answer_6-3-7.py
A, B = map(int, input().split())
print(max(A+(A-1), B+(B-1), A+B))

ABC031 A - ゲーム | 提出結果

解答例:answer_6-3-8.py
A, D = map(int, input().split())
print(max((A+1)*D, A*(D+1)))

ABC209 A - Counting | 提出結果

解答例:answer_6-3-9.py
A, B = map(int, input().split())
print(max(0, B-A+1))

ABC183 A - ReLU | 提出結果

解答例:answer_6-3-10.py
x = int(input())
print(max(0, x))

ABC072 A - Sandglass2 | 提出結果

解答例:answer_6-3-11.py
X, t = map(int, input().split())
print(max(0, X-t))

ABC143 A - Curtain | 提出結果

解答例:answer_6-3-12.py
A, B = map(int, input().split())
print(max(0, A-2*B))

ABC136 A - Transfer | 提出結果

解答例:answer_6-3-13.py
A, B, C = map(int, input().split())
print(max(0, C-(A-B)))

ABC233 A - 10yen Stamp | 提出結果

解答例:answer_6-3-14.py
import math
X, Y = map(int, input().split())
print(max(0, math.ceil((Y-X)/10)))

ABC318 A - Full Moon | 提出結果

解答例:answer_6-3-15.py
import math
N, M, P = map(int, input().split())
print(max(0, math.ceil((N-M+1)/P)))

ABC100 A - Happy Birthday! | 提出結果

解答例:answer_6-3-16.py
A, B = map(int, input().split())
if max(A, B) <= 8:
    print("Yay!")
else:
    print(":(")

ABC275 A - Find Takahashi | 提出結果

解答例:answer_6-3-17.py
N = int(input())
H = list(map(int, input().split()))
print(H.index(max(H))+1)

ABC311 A - First ABC | 提出結果

解答例:answer_6-3-18.py
N = int(input())
S = "0"+input()
print(max(S.find("A"), S.find("B"), S.find("C")))

ABC026 A - 掛け算の最大値 | 提出結果

解答例:answer_6-3-19.py
A = int(input())
ans = 0
for x in range(1, A+1):
    y = A-x
    ans = max(ans, x*y)
print(ans)

ABC383 A - Humidifier 1 | 提出結果

解答例:answer_6-3-20.py
N = int(input())
t, v = 0, 0
for _ in range(N):
    T, V = map(int, input().split())
    t, v = T, max(0, v-(T-t))+V
print(v)

ABC313 A - To Be Saikyo | 提出結果

解答例:answer_6-3-21.py
N = int(input())
P = list(map(int, input().split()))
x = 0
for i in range(1, N):
    x = max(x, P[i])
if P[0] > x:
    print(0)
else:
    print(x-P[0]+1)

6.4 最小値(min)

キーポイント

  • 最小値を得る場合、min関数を使用する。

整数の場合、min(整数A, 整数B, 整数C)となる。

サンプルコード:sample_6-4-1.py
print(min(1, 2, 3))
実行結果
1

変数の場合、min(変数A, 変数B, 変数C)となる。

サンプルコード:sample_6-4-2.py
x = 1
y = 2
z = 3
print(min(x, y, z))
実行結果
1

リストの場合、min(リスト)となる。

サンプルコード:sample_6-4-3.py
x = [1, 2, 3]
print(min(x))
実行結果
1

ABC080 A - Parking | 提出結果

解答例:answer_6-4-1.py
N, A, B = map(int, input().split())
print(min(A*N, B))

ABC133 A - T or T | 提出結果

解答例:answer_6-4-2.py
N, A, B = map(int, input().split())
print(min(N*A, B))

ABC066 A - ringring | 提出結果

解答例:answer_6-4-3.py
a, b, c = map(int, input().split())
print(min(a+b, b+c, c+a))

ABC129 A - Airplane | 提出結果

解答例:answer_6-4-4.py
P, Q, R = map(int, input().split())
print(min(P+Q, Q+R, R+P))

ABC092 A - Traveling Budget | 提出結果

解答例:answer_6-4-5.py
A, B, C, D = [int(input()) for i in range(4)]
print(min(A, B)+min(C, D))

ABC120 A - Favorite Sound | 提出結果

解答例:answer_6-4-6.py
A, B, C = map(int, input().split())
print(min(C, B//A))

ABC040 A - 赤赤赤赤青 | 提出結果

解答例:answer_6-4-7.py
n, x = map(int, input().split())
print(min(x-1, n-x))

ABC185 A - ABC Preparation | 提出結果

解答例:answer_6-4-8.py
A = list(map(int, input().split()))
print(min(A))

ABC103 A - Task Scheduling Problem | 提出結果

解答例:answer_6-4-9.py
A = list(map(int, input().split()))
print(max(A)-min(A))

ABC310 A - Order Something Else | 提出結果

解答例:answer_6-4-10.py
N, P, Q = map(int, input().split())
D = list(map(int, input().split()))
print(min(P, Q+min(D)))

ABC362 A - Buy a Pen | 提出結果

解答例:answer_6-4-11.py
R, G, B = map(int, input().split())
C = input()
if C == "Red":
    print(min(G, B))
if C == "Green":
    print(min(R, B))
if C == "Blue":
    print(min(R, G))

ABC261 A - Intersection | 提出結果

解答例:answer_6-4-12.py
L1, R1, L2, R2 = map(int, input().split())
print(max(0, min(R1, R2)-max(L1, L2)))

6.5 合計値(sum)

キーポイント

  • 合計値を得る場合、sum関数を使用する。

リストの要素の合計値を得る場合、sum(リスト)となる。

サンプルコード:sample_6-5-1.py
x = [1, 2, 3]
print(sum(x))
実行結果
6

ABC272 A - Integer Sum | 提出結果

解答例:answer_6-5-1.py
N = int(input())
A = list(map(int, input().split()))
print(sum(A))

ABC147 A - Blackjack | 提出結果

解答例:answer_6-5-2.py
A = list(map(int, input().split()))
if sum(A) >= 22:
    print("bust")
else:
    print("win")

ABC202 A - Three Dice | 提出結果

解答例:answer_6-5-3.py
abc = list(map(int, input().split()))
print(21-sum(abc))

ABC351 A - The bottom of the ninth | 提出結果

解答例:answer_6-5-4.py
A = list(map(int, input().split()))
B = list(map(int, input().split()))
print(sum(A)-sum(B)+1)

ABC349 A - Zero Sum Game | 提出結果

解答例:answer_6-5-5.py
N = int(input())
A = list(map(int, input().split()))
print(0-sum(A))

ABC066 A - ringring | 提出結果

解答例:answer_6-5-6.py
abc = list(map(int, input().split()))
print(sum(sorted(abc)[:2]))

ABC403 A - Odd Position Sum | 提出結果

解答例:answer_6-5-7.py
N = int(input())
A = list(map(int, input().split()))
print(sum(A[::2]))

ABC307 A - Weekly Records | 提出結果

解答例:answer_6-5-8.py
N = int(input())
A = list(map(int, input().split()))
for i in range(N):
    print(sum(A[i*7:(i+1)*7]), end=" ")

数字和

map関数を使用して、sum(map(int, 整数の文字列データ))で数字和を求めることができる。

サンプルコード:sample_6-5-2.py
x = 1234
print(sum(map(int, str(x))))
実行結果
10
サンプルコード:sample_6-5-3.py
x = "1234"
print(sum(map(int, x)))
実行結果
10

ABC023 A - 加算王 | 提出結果

解答例:answer_6-5-9.py
X = input()
print(sum(map(int, X)))

ABC187 A - Large Digits | 提出結果

解答例:answer_6-5-10.py
A, B = input().split()
a = sum(map(int, A))
b = sum(map(int, B))
if a > b:
    print(a)
else:
    print(b)

ABC248 A - Lacked Number | 提出結果

解答例:answer_6-5-11.py
S = input()
print(45-sum(map(int, S)))

6.6 絶対値(abs)

キーポイント

  • 絶対値を得る場合、abs関数を使用する。

絶対値を得る場合、abs(数値)となる。

サンプルコード:sample_6-6-1.py
x = -1
print(abs(x))
実行結果
1
サンプルコード:sample_6-6-2.py
x = -1.1
print(abs(x))
実行結果
1.1

ABC071 A - Meal Delivery | 提出結果

解答例:answer_6-6-1.py
x, a, b = map(int, input().split())
if abs(a-x) < abs(b-x):
    print("A")
else:
    print("B")

ABC188 A - Three-Point Shot | 提出結果

解答例:answer_6-6-2.py
X, Y = map(int, input().split())
if abs(X-Y) < 3:
    print("Yes")
else:
    print("No")

ABC123 A - Five Antennas | 提出結果

解答例:answer_6-6-3.py
a, b, c, d, e, k = [int(input()) for i in range(6)]
if abs(a-e) <= k:
    print("Yay!")
else:
    print(":(")

ABC097 A - Colorful Transceivers | 提出結果

解答例:answer_6-6-4.py
a, b, c, d = map(int, input().split())
if abs(a-c) <= d or (abs(a-b) <= d and abs(b-c) <= d):
    print("Yes")
else:
    print("No")

ABC305 A - Water Station | 提出結果

解答例:answer_6-6-5.py
N = int(input())
dist = 100
for i in range(0, 101, 5):
    if abs(N-dist) > abs(N-i):
        dist = i
print(dist)

6.7 文字(ord/chr)

キーポイント

  • 文字の Unicode コードポイントを得る場合、ord関数を使用する。
  • Unicode コードポイントの文字を得る場合、chr関数を使用する。

文字の Unicode コードポイントを得る場合、ord(文字)となる。Unicode コードポイントの文字を得る場合、chr(整数)となる。

サンプルコード:sample_6-7-1.py
x = "a"
print(ord(x))
実行結果
97
サンプルコード:sample_6-7-2.py
x = 97
print(chr(x))
実行結果
a
サンプルコード:sample_6-7-3.py
x = "A"
print(ord(x))
実行結果
65
サンプルコード:sample_6-7-4.py
x = 65
print(chr(x))
実行結果
A

ABC252 A - ASCII code | 提出結果

解答例:answer_6-7-1.py
N = int(input())
print(chr(N))

ABC151 A - Next Alphabet | 提出結果

解答例:answer_6-7-2.py
C = input()
print(chr(ord(C)+1))

ABC402 A - CBC | 提出結果

解答例:answer_6-7-3.py
S = input()
ans = ""
for s in S:
    if ord("A") <= ord(s) <= ord("Z"):
        ans += s
print(ans)

ABC282 A - Generalized ABC | 提出結果

解答例:answer_6-7-4.py
K = int(input())
s = ""
for i in range(K):
    s += chr(ord("A")+i)
print(s)

ABC404 A - Not Found | 提出結果

解答例:answer_6-7-5.py
S = input()
for i in range(26):
    if chr(i+ord("a")) not in S:
        print(chr(i+ord("a")))
        break

ABC257 A - A to Z String 2 | 提出結果 | 提出結果

解答例:answer_6-7-6.py
N, X = map(int, input().split())
print(chr(ord("A")+(X-1)//N))
解答例:answer_6-7-7.py
N, X = map(int, input().split())
string = ""
for i in range(26):
    for j in range(N):
        string += chr(ord("A")+i)
print(string[X-1])

第7章 関数定義

第7章では関数定義について説明します。

7.1 関数定義

キーポイント

  • 関数はdefで定義する。
  • def文で関数名と引数名を指定する。
  • 返り値(戻り値)はreturn文で指定する。
  • return文を指定しない場合、Noneが返る。

関数はdefで定義する。def文で関数名と引数名を指定する。返り値(戻り値)はreturn文で指定する。

サンプルコード:sample_7-1-1.py
def add(a, b):
    return a+b


print(add(1, 2))
実行結果
3

ABC234 A - Weird Function | 提出結果

解答例:answer_7-1-1.py
def f(x):
    return x**2+2*x+3


t = int(input())
print(f(f(f(t)+t)+f(f(t))))

return文を指定しない場合、Noneが返る。

サンプルコード:sample_7-1-2.py
def add(a, b):
    print(a+b)


print(add(1, 2))
実行結果
3
None
サンプルコード:sample_7-1-3.py
def add(a, b):
    print(a+b)


add(1, 2)
実行結果
3

7.2 再帰関数

再帰関数は下記のように記述することできる。

サンプルコード:sample_7-2-1.py
def factorial(N):
    if N == 0:
        return 1
    else:
        return N*factorial(N-1)


print(factorial(4))
実行結果
24
サンプルコード:sample_7-2-2.py
def fibonacci(N):
    if N == 0:
        return 0
    elif N == 1:
        return 1
    else:
        return fibonacci(N-1)+fibonacci(N-2)


print(fibonacci(10))
実行結果
55

ABC273 A - A Recursive Function | 提出結果

解答例:answer_7-2-1.py
def f(x):
    if x == 0:
        return 1
    else:
        return x*f(x-1)


N = int(input())
print(f(N))

付録

付録では Python の学習を深める情報について説明します。

オブジェクトの型を確認する

オブジェクトの型を確認する場合、type関数を使用する。

サンプルコード:appendix_1-1.py
x = 10
print(x)
print(type(x))
実行結果
10
<class 'int'>
サンプルコード:appendix_1-2.py
x = 20.5
print(x)
print(type(x))
実行結果
20.5
<class 'float'>
サンプルコード:appendix_1-3.py
x = "Hello world!"
print(x)
print(type(x))
実行結果
Hello world!
<class 'str'>
サンプルコード:appendix_1-4.py
x = [1, 2, 3, 4, 5]
print(x)
print(type(x))
実行結果
[1, 2, 3, 4, 5]
<class 'list'>
サンプルコード:appendix_1-5.py
x = (1, 2, 3, 4, 5)
print(x)
print(type(x))
実行結果
(1, 2, 3, 4, 5)
<class 'tuple'>
サンプルコード:appendix_1-6.py
x = {1, 2, 3, 4, 5}
print(x)
print(type(x))
実行結果
{1, 2, 3, 4, 5}
<class 'set'>
サンプルコード:appendix_1-7.py
x = {"one": 1, "two": 2, "three": 3}
print(x)
print(type(x))
実行結果
{'one': 1, 'two': 2, 'three': 3}
<class 'dict'>

エラーの例

エラーの例を紹介します。

  • 全角スペースがある
サンプルコード:appendix_2-1.py
print( )  # 全角スペースを出力している
実行結果
    print( )  # 全角スペースを出力している
          ^
SyntaxError: invalid non-printable character U+3000
  • 括弧を閉じていない
サンプルコード:appendix_2-2.py
print(
実行結果
    print(
         ^
SyntaxError: '(' was never closed
  • ダブルクォーテーション(またはシングルクォーテーション)を閉じていない
サンプルコード:appendix_2-3.py
x = "a
実行結果
    x = "a
        ^
SyntaxError: unterminated string literal (detected at line X)
  • コロンがない
サンプルコード:appendix_2-4.py
if True
    print()
実行結果
    if True
           ^
SyntaxError: expected ':'
  • インデントを間違える
サンプルコード:appendix_2-5.py
print()
 print()
実行結果
    print()
IndentationError: unexpected indent
  • スペルを間違える
サンプルコード:appendix_2-6.py
pirnt()
実行結果
    pirnt()
    ^^^^^
NameError: name 'pirnt' is not defined. Did you mean: 'print'?
  • ゼロで割る
サンプルコード:appendix_2-7.py
print(1/0)
実行結果
    print(1/0)
          ~^~
ZeroDivisionError: division by zero
  • ゼロで余りを求める
サンプルコード:appendix_2-8.py
print(1 % 0)
実行結果
    print(1 % 0)
          ~~^~~
ZeroDivisionError: integer modulo by zero
  • 範囲外を参照する
サンプルコード:appendix_2-9.py
x = ["a"]
print(x[1])
実行結果
    print(x[1])
          ~^^^
IndexError: list index out of range
サンプルコード:appendix_2-10.py
x = "a"
print(x[1])
実行結果
    print(x[1])
          ~^^^
IndexError: string index out of range
サンプルコード:appendix_2-11.py
x = ["a"]
print(x.pop(1))
実行結果
    print(x.pop(1))
          ^^^^^^^^
IndexError: pop index out of range
  • 存在しない要素を探索する
サンプルコード:appendix_2-12.py
x = ["a"]
print(x.index("b"))
実行結果
    print(x.index("b"))
          ^^^^^^^^^^^^
ValueError: 'b' is not in list
  • 存在しない文字列を探索する
サンプルコード:appendix_2-13.py
x = "a"
print(x.index("b"))
実行結果
    print(x.index("b"))
          ^^^^^^^^^^^^
ValueError: substring not found
  • 辞書に登録されていないキーを参照する
サンプルコード:appendix_2-13.py
x = {"a": 0}
print(x["b"])
実行結果
    print(x["b"])
          ~^^^^^
KeyError: 'b'
  • 空のオブジェクトから要素を取り出す
サンプルコード:appendix_2-14.py
x = []
print(x.pop())
実行結果
    print(x.pop())
          ^^^^^^^
IndexError: pop from empty list
サンプルコード:appendix_2-15.py
x = set()
print(x.pop())
実行結果
    print(x.pop())
          ^^^^^^^
KeyError: 'pop from an empty set'
888
875
20

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
888
875

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?