파이썬 알고리즘 문제 풀이

[프로그래머스]완주하지 못한 선수

gogi masidda 2023. 11. 17. 15:55
  • 완주하지 못한 선수
  • 수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.제한사항
    • 마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.
    • completion의 길이는 participant의 길이보다 1 작습니다.
    • 참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다.
    • 참가자 중에는 동명이인이 있을 수 있습니다.
  • 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.
def solution(participant, completion):
    length = len(participant)
    participant.sort()
    completion.sort()
    for i in range(len(completion)):
        if(completion[i] != participant[i]):
            return participant[i]
        
    return participant[len(completion)]

 

다른 사람 풀이

import collections

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

 

Counter는 빼기가 되는구나..

Counter

from collections import Counter

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

Counter는 중복된 데이터가 저장된 배열을 인자로 넘기면 각 원소가 몇번씩 나오는지 저장된 객체가 나온다.

문자열을 인자로 넘기면 각 문자가 몇번 나온지를 알려준다.

참고

https://www.daleseo.com/python-collections-counter/

 

파이썬 collections 모듈의 Counter 사용법

Engineering Blog by Dale Seo

www.daleseo.com

 

728x90