알고리즘 연습/구현, 문자열

[Lv.1 / 프로그래머스 / 파이썬] 가장 많이 받은 선물 (2024 KAKAO WINTER INTERNSHIP)

김세진 2024. 3. 24. 21:34
반응형

 

 

 

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

풀이

 

딕셔너리를 이용하여 주고받은 선물의 히스토리를 기록한다. 나중에 선물 지수를 계산할 때 필요하므로 자신이 선물을 몇 개 받았는지 기록하는 received 딕셔너리도 함께 기록해준다.

 

이후 친구 목록을 순회하며 두 사람의 선물 기록 및 선물 지수를 바탕으로 선물을 받을 개수를 계산하고 반환한다.

 

def solution(friends, gifts):
    # 선물 기록을 저장할 딕셔너리 생성
    history = dict() # 2depth, a = {b: 1}; a가 b에게 1개 줌
    received = dict() # 받은 개수
    for x in friends:
        history[x] = dict()
        received[x] = 0
        for y in friends:
            if x == y:
                continue
            history[x][y] = 0
    
    # 히스토리 기록
    for gift in gifts:
        a, b = gift.split()
        history[a][b] += 1
        received[b] += 1
    
    # 다음 달에 주고받을 선물 계산
    result = dict(map(lambda x: (x, 0), friends))
    for i in range(len(friends)):
        for j in range(i+1, len(friends)):
            a, b = friends[i], friends[j]
            if history[a][b] > history[b][a]:
                result[a] += 1
                continue
            elif history[a][b] < history[b][a]:
                result[b] += 1
                continue
            # 선물지수 계산
            a_score = sum(history[a].values()) - received[a]
            b_score = sum(history[b].values()) - received[b]
            if a_score > b_score:
                result[a] += 1
            elif a_score < b_score:
                result[b] += 1
                
    return(max(result.values()))

 

 

 

 

 

 

반응형