프로그래머스-완주하지 못한 선수(파이썬, python)

SA Jung·2022년 9월 30일
0

Programmers 문제 풀이

목록 보기
5/14

https://school.programmers.co.kr/learn/courses/30/lessons/42576

[git]
https://github.com/JungSangA/Algorithm_Study/blob/main/%ED%95%B4%EC%8B%9C/%EC%99%84%EC%A3%BC%ED%95%98%EC%A7%80%EB%AA%BB%ED%95%9C%20%EC%84%A0%EC%88%98.ipynb

1. sort를 통한 정렬 후 단순 비교

# sort 이용
def solution(participant, completion):
    answer = 0
    participant.sort()
    completion.sort()
    for i,j in zip(participant,completion):
        if i != j: 
            break
        answer +=1  
    return (participant[answer])
  • 참가자와 완주자의 list를 .sort()를 통해 오름차순 정렬을 한다.
  • zip 내장함수를통해 참가자와 완주자를 선형비교를 통해 이름이 같지 않을 경우, 완주를 하지 못한 것으로 판단하고 그 즉시 break를 통해 빠져나오고 방금 완주하지 못했다고 판단한 이름을 return 한다.

2. 해시 이용

# 해시 이용
from collections import defaultdict

def solution(participant, completion):
    answer = 0
    tmp_dic = defaultdict(int)
    # 참가자 이름을 키값으로 동명이인 포함하여 인원 수를 value값으로 dict에 저장
    for i in participant:
        tmp_dic[i] += 1
    # 완주자 이름을 키값으로 찾아서 value를 1을 뺀다.
    # (단, value값이 0이 되면 동명이인이 없는 것이므로 tmp_dic에서 제거)
    for i in completion:
        tmp_dic[i] -= 1
        if tmp_dic[i] == 0:
            del tmp_dic[i]
    return list(tmp_dic)[0]
  • 프로그래머스에서 해시part로 나뉘어져 있기 때문에 해시로 풀어봄이 맞지만 해시로 푸는것보다 1번 알고리즘이 더 효율적이긴 하다.
  • 해시로 이 문제를 풀어보자면 defaultdict를 통해 효율적으로 dict를 만들 수 있고, 동명이인 포함한 참가자 이름을 키값으로 하고 인원 수를 value값으로 dict에 저장한다.(동명이인인 경우 하나의 키값에 value값을 증가시킨다.)

    [defaultdict 라이브러리]
    https://velog.io/@jsanga214/%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC-%ED%95%B4%EA%B2%B0-%EB%B0%A9%EC%95%88

  • 완주자 목록을 돌면서 참가자 이름을 찾아 value를 하나씩 제거하고, 인원이 0이 됬을 경우 동명이인이 없는것으로 판단하고 dict에서 제거한다.
    최종적으로 tmp_dict에 남아있는 인원의 이름을 return 한다.
profile
Tomorrow will be better than yesterday :)

1개의 댓글

comment-user-thumbnail
약 6시간 전

Now i'm actually very happy to locate this web site and also would take pleasure in studying beneficial posts published the following. The particular tips with the creator has been great, thank you for your discuss. https://gatesofolympus2slot.com

답글 달기