[Python] collections.Counter()

sunclock·2020년 12월 29일
0

코딩테스트

목록 보기
1/3
post-thumbnail

문제

참가자 N명 이름 리스트, 완주자 N-1명 이름 리스트가 주어졌을 때 완주하지 못한 사람 이름 찾기.
단, 이름은 중복을 허용한다.

입력 예시:

참가자 = ['김준수', '손미연', '김준수']
완주자 = ['김준수', '손미연'] 

출력 예시:

'김준수' 

내가 푼 것

remove()는 리스트에서 제일 먼저 찾은 원소만 삭제한다는 점을 이용

def solution(participant, completion):
    for i in participant:
        if i in completion:
            completion.remove(i) 
        else:
            return i

다른 사람이 푼 것

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

collentions.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.

버전 3.7에서 변경: As a dict subclass, Counter Inherited the capability to remember insertion order. Math operations on Counter objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand.

Counter 만드는 방법

c = Counter()                           # a new, empty counter
c = Counter('gallahad')                 # a new counter from an iterable
c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
c = Counter(cats=4, dogs=8)             # a new counter from keyword args

없는 원소를 호출할 때 ValueError 없이 0을 반환

c = Counter(['eggs', 'ham'])
c['bacon']                              # count of a missing element is zero
0

값을 0으로 설정한다고 해서 원소가 삭제되지는 않음

c['sausage'] = 0                        # counter entry with a zero count
del c['sausage']                        # del actually removes the entry

Counter 객체는 dictionary에 사용 가능한 메소드 이외에도 추가로 3개의 메소드를 지원한다.

elements()

값만큼 원소를 반복하는 iterator를 반환한다. 원소값이 0이면 elements()를 무시한다.

c = Counter(a=4, b=2, c=0, d=-2)
sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

most_common([n])

가장 많이 등장하는 n개의 원소와 등장 횟수를 오름차순으로 반환한다.

Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

subtract([iterable-or-mapping])

원소의 등장 횟수만큼 iterable이나 mapping이나 counter에서 뺀다.

c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

Counter 사용 사례

sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts

Counter 간의 더하기, 빼기, 교집합, 합집합

주어진 문제 풀이에서 사용된 방법이다. Counter 간의 빼기가 양수 값만을 보존한다는 점을 이용했다.

c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
c - d                       # subtract **(keeping only positive counts)**
Counter({'a': 2})
c & d                       # intersection:  min(c[x], d[x]) 
Counter({'a': 1, 'b': 1})
c | d                       # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})

단항 덧셈과 단항 뺄셈은 빈 카운터를 더하거나 빈 카운터에서 빼는 작업을 빠르게 한다.

c = Counter(a=2, b=-4)
+c
Counter({'a': 2})
-c
Counter({'b': 4})

출처

문제: 프로그래머스 코딩테스트 연습 해시 1단계
설명: 파이썬 공식 문서

profile
안녕하세요.

0개의 댓글