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 객체 끼리의 뺄셈 연산이 가능하다는 것을 알게 되었다.
print(collections.Counter(participant))
print(collections.Counter(completion))
print(collections.Counter(participant) - collections.Counter(completion))
이처럼 participant와 completion의 요소들로 각각 Counter객체를 만들어서 뺄셈 연산을 하는 과정을 각각 출력해보면
이와 같은 결과가 나온다.
Counter객체를 뺄 때는 우선 key가 맞는지 확인하고 맞다면 value값을 빼주는 방식인 것으로 보인다.
이와 같은 결과가 나오는 걸 볼 수 있는데, 이건 Counter 객체의 뺄셈연산은 차집합 연산과 같다고 볼 수 있다.
문제 자체는 쉬운 문제였는데, 요즘 쉬운 문제일수록 다른 사람들의 코드를 보면서 새로 알아가는 문법이 많아지는 것 같아서 좋다.
어려운 문제를 풀 때는 아이디어 자체를 떠올리기 어려워서 문법을 신경쓸 겨를이 없었는데 말이다~~