[pro] 완주하지 못한 선수

letsbebrave·2022년 5월 23일
0

codingtest

목록 보기
131/146

문제

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

풀이

def solution(participant, completion):
    dict = {} # 이름 :  명 수
    
    for i in participant :
        if i in dict: # 해당 이름이 dict에 key 값으로 존재한다면
            dict[i] = dict.get(i) + 1
        else :
            dict[i] = 1
    
    for i in completion: # 완주자 key의 value는 하나씩 빼줌
        dict[i] = dict.get(i) - 1
        
    answer = ''
    
    for i in dict.keys():
        if dict.get(i) > 0:
            answer = i
            
    return answer

다른 사람 풀이(by gon2)

from collections import Counter
def solution(participant, completion):

    p_count = Counter(participant)
    # Counter({'mislav': 2, 'stanko': 1, 'ana': 1})
    c_count = Counter(completion)

    # counter 간에는 집합처럼 연산 가능
    result = p_count-c_count
    # Counter({'vinko': 1})

    # 반드시 한명은 남으니 most_common(1)로 남아있는 한명을 꺼낸다.
    # 가장 수가 많은 3명을 뽑을 때는 most_common(3)
    answer = result.most_common(1)
    # [('leo', 1)]
    answer = answer[0][0]


    return answer

collections.Counter를 이용한 카운팅

from collections import Counter

Counter('hello world') 
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

most_common(k)

데이터의 개수가 많은 순으로 정렬된 배열을 리턴하는 most_common( )이라는 메서드

from collections import Counter

Counter('hello world').most_common() 
# [('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]

인자 k 값을 넣으면 그 숫자만큼만 리턴하므로, 가장 개수가 많은 k개의 데이터를 얻을 수 있음

from collections import Counter

Counter('hello world').most_common(1)
# [('l', 3)]
profile
그게, 할 수 있다고 믿어야 해

0개의 댓글