[Programmers] 해시 > 완주하지 못한 선수

hizzang·2021년 8월 22일
0
post-thumbnail

문제링크

https://programmers.co.kr/learn/courses/30/lessons/42576

제출코드

ver1 (배열을 이용한 풀이)

def solution(participant, completion):
    participant.sort()
    completion.sort()
    for i in range(len(completion)):
        if participant[i] != completion[i]:
            return participant[i]
    return participant[-1]

ver2 (해시를 이용한 풀이)

import collections


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

정리

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

  • Counter는 해시 가능한 객체를 세기 위한 dict 서브 클래스이다.
  • 항목(요소)의 개수를 세기 위해 사용하는 클래스이다.
  • 요소가 딕셔너리 키로 저장되고 개수가 딕셔너리값으로 저장된다.
  • 객체는 누락된 항목에 대해 KeyError를 발생시키는 대신 0을 반환한다.
[참고url] https://docs.python.org/ko/3/library/collections.html

📌 두 개의 Counter 간 덧셈, 뺄셈 가능
: 뺄셈의 경우 음수 값은 출력하지 않음

c = Counter(a=3, b=1)
d = Counter(a=1, b=2)

c + d
#결과: Counter({'a': 4, 'b': 3})

c - d                     
#결과: Counter({'a': 2})

📌 교집합(&), 합집합(|) 연산 가능
: 출력값은 {요소 : 개수}의 딕셔너리 형태로 반환

c = Counter(a=3, b=1)
d = Counter(a=1, b=2)

c & d 
#결과: Counter({'a': 1, 'b': 1})

c | d
#결과: Counter({'a': 3, 'b': 2})

📌 most_common(n)
: 상위 n개 요소 추출
: n인자를 주지 않으면 전체 요소가 출력됨
: 가장 흔한 것부터 가장 적은 것 순으로 나열한 리스트를 반환

Counter('abracadabra').most_common(3)

#결과: [('a', 5), ('b', 2), ('r', 2)]

📌 elements()
: 반복되는 요소에 개수만큼 반환
: 요소는 처음 발견되는 순서대로 반환
: 요소의 개수가 1보다 작으면 elements()는 이를 무시

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

#결과: ['a', 'a', 'a', 'a', 'b', 'b']

📌 subtract()
: 말 그대로 요소를 빼는것을 의미
: 요소가 없는 경우는 음수의 값이 출력

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})

0개의 댓글