관리 메뉴

오늘도 배운다

완주하지 못한 선수 / 프로그래머스, 파이썬 코딩테스트 연습 해시 본문

코딩테스트연습(파이썬)

완주하지 못한 선수 / 프로그래머스, 파이썬 코딩테스트 연습 해시

LearnerToRunner 2022. 12. 5. 08:30

문제

수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.

 

 

제출답안

def solution(participant, completion):
    participant, completion = sorted(participant), sorted(completion)
    i= 0
    while(1):
        if participant[i] != completion[i]:
            answer = participant[i]
            break
        i+=1
        if i == len(completion):
            answer = participant[-1]
            break
    return answer

 

 

제출 후 개선답안

다른 사람의 풀이 결과를 통해 collections를 알게됨.

a. collections.Counter를 쓰면 리스트 내 값과 빈도수를 딕셔너리 형태로 나타남
b. collection.Counter 결과끼리 더하기, 빼기가 됨


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

 

개선 전 후 코드 처리 결과

 

문제 바로가기

 

728x90
Comments