최대 1 분 소요

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

.

처음 풀이(런타임 에러)

def solution(N, stages):
    stages.sort()
    failure_dict = {i + 1 : 0 for i in range(N)}
    stages_len = len(stages)
    for i in range(1, N + 1) :
        failure = stages.count(i) / stages_len
        failure_dict[i] = failure
        stages_len -= stages.count(i)
    
    sorted_by_value = [key for key, value in sorted(failure_dict.items(), key = lambda x : x[1], reverse = True)]
    
    return sorted_by_value

이렇게 코드를 제출하니 30%정도의 테스트 케이스에서 런타임 에러가 났다. 그 이유는 예를 들어,

N, stages = 5, [1, 1, 1, 1, 1]

이라고 입력데이터가 주어졌을 때, 2부터는 실패율 계산할 때의 분모가 0이 되므로 런타임 에러가 났던 것이다.

고친 풀이(정답)

def solution(N, stages):
    stages.sort()
    failure_dict = {i + 1 : 0 for i in range(N)}
    stages_len = len(stages)
    for i in range(1, N + 1) :
        if stages_len != 0 :
            failure = stages.count(i) / stages_len
            failure_dict[i] = failure
            stages_len -= stages.count(i)
        else :
            failure_dict[i] = 0
    
    sorted_by_value = [key for key, value in sorted(failure_dict.items(), key = lambda x : x[1], reverse = True)]
    
    return sorted_by_value

댓글남기기