LoginSignup
1
1

More than 1 year has passed since last update.

Python ライブラリ まとめ

Last updated at Posted at 2022-08-22

はじめに

atcoderでpythonを使う際に軽くみるためのメモ程度のもの
(僕が勉強すればするほど更新されていきます。頑張ります)
競技プログラミング初心者の方、活用していただけると嬉しいです!

itertools

import itertools

pythonでは標準ライブラリを上記のようにimport文を記述してから利用

【累積和】 itertools.accumulate()

ある区間の合計を求めたい時などは累積和を用いることで解けることが多い。

num = [1, 2, 3, 6]
a = itertools.accumulate(num)

for i in a:
    print(i)
# 出力
# 1
# 3
# 6
# 12

listやsetにも簡単に型変換可能

b = list(itertools.accumulate(num))
print(b)
# [1, 3, 6, 12]

【組み合わせ】 itertools.combinations()

全ての組み合わせを作成してくれるやつ

a = itertools.combinations(range(1,5), 3)

for i in a:
    print(*i)
# 出力
#1 2 3
#1 2 4
#1 3 4
#2 3 4

第1引数・・・対象の配列
第2引数・・・何個ずつ取り出すか
*補足
range(1,5): [1,2,3,4]のlist
*i: 括弧などの記号をなしで出力する

【グループ化】 itertools.groupby()

ランレングス圧縮などで使われる

l = 'aabbccdeee'
for k, g in itertools.groupby(l):
    print(k, list(g))

# 出力
# a ['a', 'a']
# b ['b', 'b']
# c ['c', 'c']
# d ['d']
# e ['e', 'e', 'e']

itertools.groupby()はキーとグループを返すため、グループをlistなどで取得するためには上記のように型変換を行わなければならない。

collections

Counterクラス

from collections import Counter

配列内の数字(文字でも可)の出現回数を数え出し辞書型のようにしたもの。

num = [1, 2, 1, 1, 2]
num_counter = Counter(num)
print(num_counter)
# Counter({1: 3, 2: 2})

辞書型のサブクラスであるため、辞書型のメソッドを使うこともできる。
values() keys() items()etc...
for文でループすることも可能。

math

import math

三角関数

# math.atan2(b, a) => tanθ = b/a の θを求める
theta = math.atan2(b, a)

# math.radians(a) => a度のラジアンを求める 
theta = math.radians(180)

補足
2πラジアン = 360°

heapq (優先度付きキュー)

以下の記事の引用

優先度付きキュー (Priority queue) はデータ型の一つで、具体的には
・最小値(最大値)を O(logN)O(log⁡N)で取り出す
・要素を O(logN)O(log⁡N) で挿入する
ことが出来ます。
通常のリストだとそれぞれ O(N)O(N) ですので高速です。
「リストの要素の挿入」と「最小値(最大値)を取り出す」ことを繰り返すような時に使います。

1
1
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
1
1