문제

 

내가 작성한 코드
def solution(participant, completion):
    participant.sort()
    completion.sort()
    
    for i in range(len(completion)):
        if participant[i] != completion[i]:
            return participant[i]
    return participant[-1]

 

코드 설명
participant.sort()
completion.sort()

> participant.sort() : 참가자 명단을 오름차순으로 정렬하였습니다.

> completion.sort() : 완주자 명단을 오름차순으로 정렬하였습니다.

> 이름 순으로 정렬을 하면, participant 명단과 completion 명단에서 같은 index이지만 이름이 다른 두 명을 찾을 수 있기 때문입니다.

 

for i in range(len(completion)):
    if participant[i] != completion[i]:
        return participant[i]
return participant[-1]

> completion 길이 만큼 반복문을 진행하였습니다. completion 명단이 participant 길이보다 짧기 때문에 index error가 발생하지 않기 때문입니다.

> if 문을 사용하여 같은 index 이지만 이름이 다를 때 participant 명단에서 완주하지 못한 사람을 추출할 수 있습니다. 

> 마지막 participant[-1]은 완주하지 못한 사람이 participant 명단 맨 마지막에 있는 경우 반복문에서 찾지 못하기 때문에 따로 빼서 코드를 작성하였습니다.

 

참고할만한 코드
import collections

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

> Counter 함수를 알았지만, 이처럼 다른 Counter 함수를 적용한 것끼리 뺄 수 있음을 처음 알게 되었습니다.

> 마지막 answer.keys() 를 적용하면 dict로 적용된 key 값인 사람 이름을 추출할 수 있습니다.

> 나중에 사용할 수 있으면 사용해보자!!

+ Recent posts