2021 KAKAO BLIND RECRUITMENT 메뉴 리뉴얼 문제를 푸는데, 다른 사람의 풀이를 보니까 파이썬 모듈을 적절하게 잘 써서 코드를 굉장히 깔끔하게 짠 것을 보고 자극을 받았다.
특히 Counter 모듈을 사용하였는데, most_common() 함수를 사용했다. 알아두면 유용할 것 같아 정리하려고 한다.
Counter
hash 객체를 세기 위한 dictionary 보조 클래스이다. 요소는 dictionary key로 저장되고 개수가 dictionary value로 저장된다.
from collections import Counter # a new, empty counter a = Counter() # a new counter from an iterable b = Counter('gallahad') print(b['a']) # 3 print(b['l']) # 2 # a new counter from a mapping c = Counter({'red': 4, 'blue': 2}) print(c['red']) # 4 # a new counter from keyword args d = Counter(cats=4, dogs=8) print(d['cats']) # 4 # a new counter from list objects e = Counter(['eggs', 'ham']) print(e['eggs']) # 1 print(e['bacon']) # 0
Counter methods
elements()
c = Counter(a=4, b=2, c=0, d=-2) print(sorted(c.elements())) # ['a', 'a', 'a', 'a', 'b', 'b']
most_common([n])
가장 많은 요소 n개와 요소의 개수를 반환. n은 생략가능
c = Counter('abracadabra').most_common(3) [('a', 5), ('b', 2), ('r', 2)]
subtract([iterable-or-mapping])
c = Counter(a=4, b=2, c=0, d=-2) d = Counter(a=1, b=2, c=3, d=4) c.subtract(d) print(c) # Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
Common patterns for working with Counter objects
# total of all counts sum(c.values()) # reset all counts c.clear() # list unique elements list(c) # convert to a set set(c) # convert to a regular dictionary dict(c) # convert to a list of (elem, cnt) pairs c.items() # convert from a list of (elem, cnt) pairs Counter(dict(list_of_pairs)) # n least common elements c.most_common()[:-n-1:-1] # remove zero and negative counts +c
# 실제 적용 b = Counter('gallahad') print(set(b)) # {'g', 'h', 'l', 'a', 'd'} print(dict(b)) # {'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1} print(b.items()) # dict_items([('g', 1), ('a', 3), ('l', 2), ('h', 1), ('d', 1)]) print(b.most_common()) # [('a', 3), ('l', 2), ('g', 1), ('h', 1), ('d', 1)]
Common patterns for working with Counter objects(mathematical operations)
c = Counter(a=3, b=1) d = Counter(a=1, b=2, c=1) print(c+d) # Counter({'a': 4, 'b': 3, 'c': 1}) print(c-d) # Counter({'a': 2, 'b': -1, 'c': -1}) print(c&d) # Intersection: min(c[x], d[x]) # Counter({'a': 1, 'b': 1}) print(c|d) # union: max(c[x], d[x]) # Counter({'a': 3, 'b': 2}) # Unary addition and subtraction e = Counter(a=2, b=-4) print(+e) # Counter({'a': 2}) print(-e) # Counter({'b': 4})