코딩테스트 연습 | 프로그래머스 (programmers.co.kr)
해시 문제
문제 설명
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.
마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.
제한사항
입출력 예
participant | completion | return |
["leo", "kiki", "eden"] | ["eden", "kiki"] | "leo" |
["marina", "josipa", "nikola", "vinko", "filipa"] | ["josipa", "filipa", "marina", "nikola"] | "vinko" |
["mislav", "stanko", "mislav", "ana"] | ["stanko", "ana", "mislav"] | "mislav" |
입출력 예 설명
예제 #1
"leo"는 참여자 명단에는 있지만, 완주자 명단에는 없기 때문에 완주하지 못했습니다.
예제 #2
"vinko"는 참여자 명단에는 있지만, 완주자 명단에는 없기 때문에 완주하지 못했습니다.
예제 #3
"mislav"는 참여자 명단에는 두 명이 있지만, 완주자 명단에는 한 명밖에 없기 때문에 한명은 완주하지 못했습니다.
import collections
def solution(participant, completion):
answer = collections.Counter(participant) - collections.Counter(completion)
return list(answer.keys())[0]
파이썬 공식문서: collections — Container datatypes — Python 3.9.4 documentation
collections — Container datatypes — Python 3.9.4 documentation
collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() factory f
docs.python.org
Counter: dict subclass for counting hashable objects
Sidetrack: But, can you do subtraction with dictionary in python?
dictionary - Python. How to subtract 2 dictionaries - Stack Overflow
A={'11': 3, '10': 2, '12': 1}
B={'11': 2}
But to answer you question, to do A - B (based on dict keys):
all(map(A.pop, B)) # use all() so it works for Python 2 and 3.
print(A) # {'10': 2, '12': 1}
[문자열] 1120번 (0) | 2021.04.29 |
---|---|
알고리즘 공부 추천 순서 (0) | 2021.04.29 |
Attention (youtube link) (0) | 2021.04.13 |
알고리즘 공부 사이트 (0) | 2021.04.08 |
전이학습 전략 (0) | 2021.04.06 |