코테 공부/프로그래머스

[Python/해시] 완주하지 못한 선수

prefer_all 2021. 8. 5. 00:32

문제:

한 명의 선수를 제외하고 모든 선수 마라톤 완주. 참여한 선수가 담긴 배열 participant, 완주한 선수가 담긴 배열 completion

-> 완주하지 못한 선수의 이름을 return하는 solution 함수를 작성하라

* 동명이인이 있을 수 있음   -> 집합 사용 불가

 

 

내 답안

def solution(participant, completion):
    participant.sort()
    completion.sort()
    for p, c in zip(participant, completion):
        if p != c: #동명이인이 있는 경우
            return p
    return participant[-1] #동명이인이 없는 경우

* sort() 함수: a= [c,b,a]

                 a.sort()

                 a= [a,b,c]

* zip() 함수: 객체가 담고 있는 원소를 tuple 형태로 차례로 접근할 수 있도록 iterator 반환

>>> a = [1, 2, 3]
>>> b = ["A", "B", "C"]
>>> for pair in zip(a,b):
...     print(pair)
...
(1, 'A')
(2, 'B')
(3, 'C')

 

a, b의 원소 갯수가 다를 경우

>>> a = [1, 2, 3]
>>> b = ["A", "B", "C","D"]
>>> for pair in zip(a,b):
...     print(pair)
...
(1, 'A')
(2, 'B')
(3, 'C')
# 'D'는 무시됨

 

 


다른 풀이

import collections

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

 

* collections.Counter은 컨테이너에 동일한 값의 자료가 몇개인지를 파악하는데 사용하는 객체임

>>> a = [1, 2, 3, 1]
>>> collections.Counter(a)
...     print(pair)
...
{'a':2, 'b':1, 'c':1}

 

>>participant = ["leo", "kiki", "eden"]
>>completion = ["eden", "kiki"]

>>import collections

>>def solution(participant, completion):
>>    answer = collections.Counter(participant) - collections.Counter(completion)
>>    return answer

...
...
{"leo":1}

 

[참고] https://excelsior-cjh.tistory.com/94

 

'코테 공부 > 프로그래머스' 카테고리의 다른 글

[Python/완전탐색] 카펫  (0) 2022.08.02
[Python] 행렬의 덧셈  (0) 2022.08.02
[Python] 신고 결과 받기  (0) 2022.06.21
[Python] 가장 큰 수(어려웠음)  (0) 2021.08.09
[Python] 정렬/k번째 수  (0) 2021.08.06