반응형

 

 

 

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

 

 

사실 조건은 4개로 보아야 함

 

 

 

 

오랜만에 +2점...!

 

from functools import cmp_to_key
def cmp_sum(x, y):
    return y[1] - x[1]
def cmp_by_condition(x, y):
    x_index, x_play = x
    y_index, y_play = y
    if x_play == y_play:
        return x_index - y_index
    else:
        return y_play - x_play

def solution(genres, plays):
    answer = []
    _dict1 = dict()
    _dict2 = dict()
    for i, (genre, play) in enumerate(zip(genres, plays)) :
        if genre not in _dict1.keys():
            _dict1[genre] = [(i, play)]
            _dict2[genre] = play
        else:
            _dict1[genre].append((i, play))
            _dict2[genre] += play
    tmp = sorted(_dict2.items(), key=cmp_to_key(cmp_sum))
    for (genre, _) in tmp:
        new = [x[0] for x in sorted(_dict1[genre], key=cmp_to_key(cmp_by_condition))]
        answer += new[:2]
    return answer

 

 

추천풀이 중 내가 생각했던 방법이랑 비슷했던 풀이

 

def solution(genres, plays):
    answer = []

    dic1 = {}
    dic2 = {}

    for i, (g, p) in enumerate(zip(genres, plays)):
        if g not in dic1:
            dic1[g] = [(i, p)]
        else:
            dic1[g].append((i, p))

        if g not in dic2:
            dic2[g] = p
        else:
            dic2[g] += p

    for (k, v) in sorted(dic2.items(), key=lambda x:x[1], reverse=True):
        for (i, p) in sorted(dic1[k], key=lambda x:x[1], reverse=True)[:2]:
            answer.append(i)

    return answer
반응형

+ Recent posts