Algorithm/programmers/해시/level1/완주하지 못한 선수 (with python)

yellow·2021년 6월 9일
0

알고리즘 문제

목록 보기
30/58

📖 문제

📝 풀이과정

  1. 완주를 한 선수들로 딕셔너리를 만든다.
    "key"는 선수 이름, "value"는 이 이름을 가진 사람 수
  2. 참가자들 리스트를 순회하면서 완주를 못한 사람을 찾는다.
    참가자 이름이 1.의 딕셔너리에 있다면 value를 -1
    참가자 이름이 1.의 딕셔너리에 있지만 value가 0이라면 완주를 못한 선수
    참가자 이름이 1.의 딕셔너리에 없다면 완주를 못한 선수이다.

⌨ 코드

def solution(participant, completion):
    answer = ""
    completions = dict()

    # 1. 완주를 한 선수들로 딕셔너리를 만든다.
    for person in completion:
        if person in completions:
            completions[person] += 1
        else:
            completions[person] = 1

    # 2. 참가자들 리스트를 순회하면서 완주를 못한 사람을 찾는다.
    for person in participant:
        if person in completions:
            if completions[person] != 0:
                completions[person] -= 1
            else:
                answer = person
        else:
            answer = person
    return answer

⌨ 다른 분의 코드 -> 새로 알게된 점

import collections

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

정말 경이로운 코드...
Counter 객체 끼리의 뺄셈 연산이 가능하다는 것을 알게 되었다.

  • 예를 들어 participant = [a, b, c, d, b]이고 completion = [a, b, c, d]라 하자.
print(collections.Counter(participant))
print(collections.Counter(completion))
print(collections.Counter(participant) - collections.Counter(completion))

이처럼 participant와 completion의 요소들로 각각 Counter객체를 만들어서 뺄셈 연산을 하는 과정을 각각 출력해보면

이와 같은 결과가 나온다.
Counter객체를 뺄 때는 우선 key가 맞는지 확인하고 맞다면 value값을 빼주는 방식인 것으로 보인다.

  • 다음으로 participant = [a, b, c, d, e], completion = [a, b, c, d, f, b]라고 했을 때 앞에서 한 출력 코드를 그대로 사용해보면


이와 같은 결과가 나오는 걸 볼 수 있는데, 이건 Counter 객체의 뺄셈연산은 차집합 연산과 같다고 볼 수 있다.

☺ 느낀점

문제 자체는 쉬운 문제였는데, 요즘 쉬운 문제일수록 다른 사람들의 코드를 보면서 새로 알아가는 문법이 많아지는 것 같아서 좋다.
어려운 문제를 풀 때는 아이디어 자체를 떠올리기 어려워서 문법을 신경쓸 겨를이 없었는데 말이다~~

profile
할 수 있어! :)

0개의 댓글