본문 바로가기
개발/문제풀이

프로그래머스 '2024 KAKAO WINTER INTERNSHIP가장 많이 받은 선물' 파이썬 풀이

by beomcoder 2024. 1. 8.
728x90
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/258712

 

프로그래머스

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

programmers.co.kr

 

def solution(friends, gifts):
    history = {name: {'friends': {k: 0 for k in friends}, 'score': 0} for name in friends}
    next_month_gift = {name: 0 for name in friends}
    
    for gift in gifts:
        give, get = gift.split()
        
        history[give]['friends'][get] += 1
        history[give]['score'] += 1
        
        history[get]['friends'][give] -= 1
        history[get]['score'] -= 1
    
    for name in history.keys():
        for fname, fscore in history[name]['friends'].items():
            if fscore > 0 or (fscore == 0 and history[name]['score'] > history[fname]['score']):
                next_month_gift[name] += 1

    return max(next_month_gift.values())

 

<풀이>

history = {name: {'friends': {k: 0 for k in friends}, 'score': 0} for name in friends}
next_month_gift = {name: 0 for name in friends}

'''
사람마다 친구들의 이름과 선물을 주고받은 개수, 선물지수를 적을 딕셔너리를 만들었다.
그리고 다음달에 받은 선물의 개수를 저장할 딕셔너리도 만들었다.
'''

 

for gift in gifts:
    give, get = gift.split()

    history[give]['friends'][get] += 1
    history[give]['score'] += 1

    history[get]['friends'][give] -= 1
    history[get]['score'] -= 1

'''
선물정보리스트를 for문으로 돌면서
선물을 준사람(give)과 받은사람(get)을 구분시켜주었고,

기록에서 선물을 준사람과 받은사람의 관계에서 +를 해주었고,
선물을 준사람의 선물지수(score)를 + 해주었다.

그리고 선물을 받은 사람은 선물을 준 사람과의 관계에서 -를 해주었고,
선물을 받은사람의 선물지수를 - 해주었다.

두명의 관계에서 더 많이 준사람이 다음달에 선물을 받기 때문에 기록해주었고,
선물을 주고 받은 횟수가 같다면 선물지수를 비교해야하기 때문에 기록해주었다.
'''

 

for name in history.keys():
    for fname, fscore in history[name]['friends'].items():
        if fscore > 0 or (fscore == 0 and history[name]['score'] > history[fname]['score']):
            next_month_gift[name] += 1

return max(next_month_gift.values())

'''
기록들을 전부 돌면서, 사람마다 친구들의 관계를 비교하여 for문을 돌았다.

친구에게 준 선물횟수가 더 많거나 (fscore > 0),
선물횟수가 동점이고, 그 친구의 선물지수보다 점수가 높다면 
(fscore == 0 and history[name]['score'] > history[fname]['score'])

다음달에 선물받을 횟수를 1 증가시켜주었다.

그리고 다음달의 선물받을 수 중 가장 큰값을 리턴시켜주었다.
'''
728x90
반응형

댓글