View

문제 설명

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

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

제한사항
  • 마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.
  • completion의 길이는 participant의 길이보다 1 작습니다.
  • 참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다.
  • 참가자 중에는 동명이인이 있을 수 있습니다.
입출력 예participantcompletionreturn
["leo", "kiki", "eden"] ["eden", "kiki"] "leo"
["marina", "josipa", "nikola", "vinko", "filipa"] ["josipa", "filipa", "marina", "nikola"] "vinko"
["mislav", "stanko", "mislav", "ana"] ["stanko", "ana", "mislav"] "mislav"
입출력 예 설명

예제 #1
"leo"는 참여자 명단에는 있지만, 완주자 명단에는 없기 때문에 완주하지 못했습니다.

예제 #2
"vinko"는 참여자 명단에는 있지만, 완주자 명단에는 없기 때문에 완주하지 못했습니다.

예제 #3
"mislav"는 참여자 명단에는 두 명이 있지만, 완주자 명단에는 한 명밖에 없기 때문에 한명은 완주하지 못했습니다.

 


나의 풀이

def solution(participant, completion):
    hash_data = dict.fromkeys(participant,0) 
    # from collections import defaultdict를 사용하여,
    # hash_data = defaultdict(int)를 사용해도됨.
    
    for p in participant:
        hash_data[p] += 1
    for c in completion:
        hash_data[c] -= 1
    return list(filter(lambda x:x[1]!=0,hash_data.items()))[0][0]

다른 풀이

속도의 성능 면에서 나의 풀이가 더 속도가 빠른 것을 알 수 있다.

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

 


Counter 함수

선언 방법 (문자, 리스트, 딕셔너리, 변수 모두 가능)

c = Counter()                           # a new, empty counter
c = Counter('gallahad')                 # a new counter from an iterable
c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
c = Counter(cats=4, dogs=8)             # a new counter from keyword args
c = Counter(['eggs', 'ham'])

연산 방법

c = Counter(a=3, b=1)
d = Counter(a=1, b=2)

# 두 값의 합
>>> c + d                       # add two counters together:  c[x] + d[x]

# 모든 값의 합
c = Counter(a=10, b=5, c=0)
>>> c.total()
15

# 두값의 차(오직 양수값만)
>>> c - d                       # subtract (keeping only positive counts)

# 두 값의 차(음수 양수 포함)
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})


# 교집합(겹치는 것의 갯수)
>>> c & d                       # intersection:  min(c[x], d[x])

# 합집합(최대 갯수)
>>> c | d                       # union:  max(c[x], d[x])

# 같은 키의 값이 서로 동등하면 참
>>> c == d                      # equality:  c[x] == d[x]

# 같은 키의 값이 서로 다를 경우
>>> c <= d                      # inclusion:  c[x] <= d[x]

 

Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31