jeeyeonLIM / coding_test

Let's practice the coding test!
1 stars 0 forks source link

Level1. 완주하지 못한 선수 #50

Open jeeyeonLIM opened 3 years ago

jeeyeonLIM commented 3 years ago

문제 설명

수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.

마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.

제한사항

마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다. completion의 길이는 participant의 길이보다 1 작습니다. 참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다. 참가자 중에는 동명이인이 있을 수 있습니다.

입출력 예

image

입출력 예 설명

예제 #1

예제 #2

예제 #3

jeeyeonLIM commented 3 years ago

나의코드

def solution(participant, completion):
    #answer = ''
    for i in completion[:]: 
        participant.remove(i)
    return participant[0]
jeeyeonLIM commented 3 years ago

모범답안

Ver1. Sort 활용

def solution(participant, completion):
    participant.sort()
    completion.sort()
    for i in range(len(completion)):
        if completion[i] != participant[i]:
            return participant[i]
    return participant[len(completion)]

Ver2. index 활용 (효율성 Test X)

def solution(participant, completion):
    for x in completion:
        participant.pop(participant.index(x))
    return participant[0]
jeeyeonLIM commented 3 years ago

Ver3. Collections Counter 이용

from collections import Counter
def solution(participant, completion): 
    answer = Counter(participant) - Counter(completion) 
    return list(answer.keys())[0]
jeeyeonLIM commented 3 years ago

정통 Hash 활용하기

jeeyeonLIM commented 3 years ago

다시풀기

Hash 활용한다면 ❗ ❗ ❗ ❗

다른사람들 풀이 : collections 모듈 활용하기

내풀이 : 직접 해시맵 생성하고, 완주자기준 검사해서 value값 변화시켜가기. 마지막에 key <-> value 처리 후 값 찾기

def solution(participant, completion):

    # 해시맵 생성 - 참가자 기준으로
    part_hash = {}
    for i in participant:
        if i not in part_hash.keys():
            part_hash[i] = 1
        else :
            part_hash[i] += 1

    # 완주자 기준 검사해주기
    for i in completion:
        if i in part_hash.keys():
            part_hash[i] -= 1 # 

    # value로 key찾기 (value=1인 key가져오기)
      #  -> 이건 두가지 방법이 있어서 아래 첨부함. value로 key 찾기 방법 찾아봤는데 아래 두개가 베스트인듯.
    # method1. items + list comprehension
    key = [k for k,v in part_hash.items() if v == 1]
    return ''.join(key) # ['leo'] 형태를 'leo' 형태로 바꿔주려고

    # method2. key <-> value 뒤집은 dictionary 만들기
    reverse_dict = {v:k for k,v in part_hash.items()}
    return reverse_dict[1]