해시
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.
마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.
def solution(participant, completion):
answer = ''
participant.sort()
completion.sort()
for i in range(len(completion)):
if participant[i] != completion[i]:
answer = participant[i]
return answer
answer = participant[-1]
return answer
participant와 completion을 알파벳 순서대로 정렬한 뒤, 앞에서부터 원소를 서로 비교해나가는 방식이다. 아직 파이썬 초보라 이런 노가다(?) 알고리즘 밖에 못함 ㅠㅠ 사실 이것도 처음에 계속 오류가 났는데 알고보니 for문 안에서 return answer을 안해서 그런거였다.
import collections
def solution(participant, completion):
answer = collections.Counter(participant) - collections.Counter(completion)
return list(answer.keys())[0]
collections 모듈을 이용한 풀이방법이다. collections 모듈에는 deque, OrderedDict, defaultdict, Counter, namedtuple 모듈 등이 있는데, 이 중에서 Counter가 뭔지 알아보자.
Counter
- 시퀀스 자료형의 데이터 요소 개수를 딕셔너리 형태로 반환하는 자료구조
- 리스트나 문자열 안의 요소 중 같은 값이 몇 개 있는지 반환
- 기본 사칙연산 지원
from collections import Counter x = list("apple") Counter(x) >>> Counter({'a':1, 'p':2, 'l':1, 'e':1})
위 풀이에서는 participant와 completion을 counter로 반환하여 빼기 연산을 하였다. 그럼 완주하지 못한 선수만 남게 되는데 이때 key를 return하면 선수 이름이 구해진다.