프로그래머스 LV1 완주하지 못한 선수(해시)

프로그래머스 LV1 완주하지 못한 선수(해시)

2021, Mar 31    

프로그래머스 lv1 완주하지 못한 선수(해시)

collections.Counter() 해시 가능한 객체를 세는 데 사용하는 딕셔너리 서브 클래스


풀이

from collections import Counter

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


if __name__ == '__main__':
    participant = ["leo", "kiki", "eden"]
    completion = ["eden", "kiki"]
    print(solution(participant, completion))

collections.Counter

  • class collections.Counter([iterable-or-mapping])

Counter는 해시 가능한 객체를 세기 위한 dict 서브 클래스이다. 요소가 딕셔너리 키로 저장되고 개수가 딕셔너리값으로 저장되는 컬렉션이다.

개수는 0이나 음수를 포함하는 임의의 정숫값이 될 수 있다. Counter 클래스는 다른 언어의 백(bag)이나 멀티 셋(multiset)과 유사하다.

요소는 이터러블로부터 계산되거나 다른 매핑(또는 계수기)에서 초기화:

>>> 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
    • 누락된 항목에 대해 KeyError를 발생시키는 대신 0을 반환한다는 점을 제외하고 딕셔너리 인터페이스를 갖는다:
>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0
    • 개수를 0으로 설정해도 계수기에서 요소가 제거되지 않는다. 완전히 제거하려면 del을 사용:
c['sausage'] = 0                        # counter entry with a zero count
del c['sausage']                        # del actually removes the entry
  • 버전 3.7에서 변경: dict 서브 클래스로서, Counter는 삽입 순서를 기억하는 기능을 상속했다.

    • 계수기 객체는 모든 딕셔너리에서 사용할 수 있는 메서드 이외의 세 가지 메서드를 지원한다:
    • elements()
      • 개수만큼 반복되는 요소에 대한 이터레이터를 반환합니다. 요소는 처음 발견되는 순서대로 반환됩니다. 요소의 개수가 1보다 작으면 elements()는 이를 무시합니다.
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
    • most_common([n])
      • n 개의 가장 흔한 요소와 그 개수를 가장 흔한 것부터 가장 적은 것 순으로 나열한 리스트를 반환합니다. n이 생략되거나 None이면, most_common()은 계수기의 모든 요소를 반환합니다. 개수가 같은 요소는 처음 발견된 순서를 유지합니다:
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
    • subtract([iterable-or-mapping])
      • 이터러블이나 다른 매핑 (또는 계수기)으로부터 온 요소들을 뺍니다. dict.update()와 비슷하지만 교체하는 대신 개수를 뺍니다. 입력과 출력 모두 0이나 음수일 수 있습니다.
>>> 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

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges