1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

競技プログラミングで使えそうなクラス

Last updated at Posted at 2025-04-21

基本的な使い方

from collections import Counter

# 文字列やリストを渡すだけで、要素ごとの出現回数をカウント
c1 = Counter("abracadabra")
print(c1)
# Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})

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

主要メソッド

  • elements()
    各要素をカウント分だけ列挙するイテレータを返す。
list(c2.elements())  # [1, 2, 2, 3, 3, 3]
  • most_common()
c1.most_common(2)  # [('a', 5), ('b', 2)]
  • update(iterable_or_counter)
    追加で要素をカウント。引数にイテラブルか他の Counter。
c = Counter()
c.update("abc")
c.update(["a","b","b"])
print(c)  # Counter({'b': 3, 'a': 2, 'c': 1})
  • subtract(iterable_or_counter)
    他と同様に要素の出現数を減算。マイナスの値も保持される点に注意。
c = Counter(a=3, b=1)
c.subtract(Counter(a=1, b=2))
print(c)  # Counter({'a': 2, 'b': -1})

四則演算・集合演算

  • 足算・引き算・掛け算・割り算でほかのCounterと組み合わせ可能
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2, c=4)

print(c1 + c2)  # 足し算: Counter({'c': 4, 'a': 4, 'b': 3})
print(c2 - c1)  # 差: 出力は正の部分のみ Counter({'c': 4, 'b': 1})
print(c1 | c2)  # 同一キーの最大値を取る: Counter({'c': 4, 'a': 3, 'b': 2})
print(c1 & c2)  # 同一キーの最小値を取る: Counter({'a': 1, 'b': 1})

典型的なユースケース

words = "this is a test this is only a test".split()
freq = Counter(words)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?