파이썬 언어로 프로그래머스 문제를 풀고 나서 다른 사람들은 어떻게 풀었을까? 구경하다가 collection의 Counter 를 활용하여 간결하게 해결한 것을 보고 궁금해져서 찾아보게 되었습니다.
알고보니 collections은 알고리즘을 풀 때 유용하게 쓰이는 라이브러리였고, 앞으로도 요긴하게 쓰일 것 같아 공부하면서 정리하고자 합니다.
이번에는 Counter가 무엇인지 한 번 살펴볼까요?
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.
from collections import Counter
기본적으로 파이썬에 내장되어있는 함수이기 때문에, 따로 설치가 필요없이 import만 하면 된다.
cnt = Counter()
for word in ['wine', 'soju', 'wine', 'beer', 'soju', 'soju']:
cnt[word] += 1
print(cnt)
>>> Counter({'soju': 3, 'wine': 2, 'beer': 1})
arr = ['wine', 'soju', 'wine', 'beer', 'soju', 'soju', 'beer']
print(Counter(arr))
>>> Counter({'soju': 3, 'wine': 2, 'beer': 2}) # 2
dic = {'wine': 5, 'soju': 7, 'beer':2}
print(Counter(dic))
>>> Counter({'soju': 7, 'wine': 5, 'beer': 2})
c = Counter('chardonnay')
print(c)
>>> Counter({'a': 2, 'n': 2, 'c': 1, 'h': 1, 'r': 1, 'd': 1, 'o': 1, 'y': 1})
c = Counter(sake=4, makgeolli=8)
print(c)
>>> Counter({'makgeolli': 8, 'sake': 4})
c = Counter(['eggs', 'ham'])
print(c['bacon']) # 0
print(c['eggs']) # 1개가 존재하므로 카운팅 1
>>> 0
>>> 1
c['ham'] = 0
print(c)
>>> Counter({'eggs': 1, 'ham': 0})
# 요소 제거
del c['ham']
print(c)
>>> Counter({'eggs': 1})
c = Counter(a=4, b=2, c=0, d=-2)
sorted(c.elements())
>>> ['a', 'a', 'a', 'a', 'b', 'b']
Counter('abracadabra').most_common(3)
Counter('abracadabra').most_common()
>>> [('a', 5), ('b', 2), ('r', 2)]
>>> [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4, e=5)
c.subtract(d)
print(c)
>>> Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6, 'e': -5})
Counter(a=10, b=5, c=0).total()
>>> 15
c = Counter('banana')
d = Counter('tomato')
print(c + d)
print(c - d)
>>> Counter({'a': 4, 'n': 2, 't': 2, 'o': 2, 'b': 1, 'm': 1})
>>> Counter({'a': 2, 'n': 2, 'b': 1})
c = Counter('banana')
d = Counter('tomato')
print(c & d)
print(c | d)
>>> Counter({'a': 1})
>>> Counter({'a': 3, 'n': 2, 't': 2, 'o': 2, 'b': 1, 'm': 1})
list 뿐만 아니라 문자열을 넣어도 데이터가 몇 개인지 딕셔너리 형태로 알려주는 것이 신기했다.
다양한 메소드를 지원해주는 것도 마음에 들고 덧셈, 뺄셈, 교집합, 합집합 등 연산이 가능하다는 것 또한 매력적으로 다가왔다.
특히 most_common()가 마음에 들었는데, 사람들이 가장 많이 쓴 단어가 무엇인지 궁금할 때 쓰면 재밌을 것 같다.
Counter는 딕셔너리를 확장한 것이므로 제대로 쓰기 위해서는 기본적인 딕셔너리 활용도 잘해야겠다는 생각이 들었다.