Skip to content
Minsing Log
Go back

English Edition

What is Counter in collections?

Programming & CS

Solving the problem of the player who didn’t finish…

import collections


def solution(participant, completion):
    answer = collections.Counter(participant) - collections.Counter(completion)
    return list(answer.keys())[0]

While analyzing someone else’s code example, I learned about the Counter class in the collections module. Why on earth does subtracting this thing, converting the result to a list through keys, and accessing index 0 produce the answer?

What is Counter?

How to use it

Basics

If you pass an array containing duplicate data as an argument, you get an object that stores how many times each element appears.

>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})

For how to use it with strings, refer to the reference below.

Using arithmetic operators

What we saw in the code above was using Counter as an arithmetic operator. Addition and subtraction are possible.

counter1 = Counter(["A", "A", "B"])
counter2 = Counter(["A", "B", "B"])

counter1 + counter2
Counter({'A': 3, 'B': 3})

counter1 - counter2
Counter({'A': 1})

If the result of the subtraction is zero or negative, it is excluded from the final Counter object, so be careful when using it! The code above used this fact to identify the player who did not finish.

References

  1. https://www.daleseo.com/python-collections-counter/
  2. Image source: https://jindabang.tistory.com/9

공개 여정 구독

글이 올라오면 이메일로 보내드릴게요.

개발, 창업, 배움, 실패와 회고를 짧고 솔직하게 기록합니다. 검색으로 스쳐가는 독자가 아니라 여정을 따라오는 팬을 만들기 위한 뉴스레터입니다.

뉴스레터는 준비 중입니다. 그동안 RSS 로 구독하거나 이메일 로 알림을 요청해 주세요.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
Cloud IDE Expo Installation
Next Post
What is enumerate()?