5
11

More than 1 year has passed since last update.

pythonでのアルゴリズム、チートシート

Last updated at Posted at 2020-03-29

はじめに

これは python でアルゴリズムをとくためのチートシートです。
他の言語でよく書くけど、pythonでどうかくっけ?
みたいな人向けです

ざっくりの表

書きたいこと 実装 補足
forで2から12まで3こ飛ばしで呼ぶ for i in range(2,12,3):
読み取る str=input() 一行読み取りです
分ける str.split(区切り文字) 指定なしで空白区切り
文字列の長さを測る len(文字列)
listの中をintにする l_si_i = [int(s) for s in l_si]
ifでandを使う if(hoge and piyo)
ifでorを使う if(hoge or piyo)
if else if elif 他の時はif else そのまま
listを使う hoge = []
listから削除 list.remove(要素) 最初にヒットした要素
listに足す hoge.append("test")
listにlistを入れる hoge.extend(piyo)
listの最大値 max(list)
listの最小値 min(list)
listにあるかどうか a in list aがlistに含まれてたらTure
listにある時にインテックスの取得 list.index(要素) ないとエラー†
listのソート hoge=sorted(piyo) もともとのリストを崩さない
文字列の文字を取り出す str = "asdf" str[0] はa ()ではないので注意
多次元配列を作る list = [[0] * m for i in range(n)]
キャスト int("2") str(8)
階乗 print(math.factorial(5)) import math

正規表現

import re
print(re.search('aaa$', s))| aaaがsにあればtrue,なければfalse
a = re.sub("x","y",text)|x を yに置換

組み合わせの上の補足

名前 意味
permutations 任意の数を選んで、並び変える
combinations 任意の数を選ぶ
combinations_with_replacement 重複を許す組み合わせ
これを置き換えて使う
hoge.py
import math
import itertools
list2 = [1,2,3]
p_list = list(itertools.permutations(list2, 2))
print(p_list)
#[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
print(len(p_list))
#6
print(p_list[0][1])
#2
for v in itertools.permutations(list2,2):
    print(v)
# (1, 2)
# (1, 3)
# (2, 1)
# (2, 3)
# (3, 1)
# (3, 2)
# # v[0]やv[1]で各要素を呼ぶことも可能
for v in itertools.permutations(list2,2):
    print(v[0])

組み合わせの数だけ

from scipy.special import comb
# a = comb(n, r)
a = comb(n, r, exact=True)

#入力受け取り

n, m = map(int, input().split())
a = list(map(int, input().split()))
5
11
0

Register as a new user and use Qiita more conveniently

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