Coding Test/Python

[Programmers][코딩테스트연습/해시] 완주하지 못한 선수

수수킴 2023. 7. 17.

def solution(participant, completion):
    
    participant_dict = {name: idx for idx, name in enumerate(participant)}
    completion_dict = {name: idx for idx, name in enumerate(completion)}
    answer = set(participant_dict.keys()) - set(completion_dict.keys())
    
    return ''.join(answer)

처음엔 위와 같이 짰었다... 하지만 동명이인을 고려하지 못하였다.

동명이인이 있는 경우 dictionary로 정의하면 ["mislav", "stanko", "mislav", "ana"]의 경우 key는 mislav, stanko, ana 밖에 없기 때문이다. 즉, 중복을 고려 못함.

따라서 collections 모듈의 Counter을 사용하여 손쉽게 해결.

from collections import Counter
def solution(participant, completion):
    answer = Counter(participant) - Counter(completion)
    return ''.join(answer.keys())
더보기

Couneter 예시

>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})
 

파이썬 collections 모듈의 Counter 사용법

Engineering Blog by Dale Seo

www.daleseo.com

코테를 손쉽게 풀기 위해서는 기본으로 제공하는 파이썬 라이브러리를 좀 봐둘 필요가 있겠다...

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

댓글