[Python] 더 맵게

hyeon·2021년 2월 11일
0

Programmers

목록 보기
6/18


1 Try

총 76.2/100

import heapq
def solution(scoville, K):
    answer = 0
    heapq.heapify(scoville)

    while len(hq)>1:
        a = heapq.heappop(scoville)
        b = heapq.heappop(scoville)
        if(b < K) :
            k = a + (b*2)
            heapq.heappush(scoville, k)
            answer +=1
        else :
            return answer
    return -1
  • 예외처리가 되지 못한 케이스는 무엇?
    가장 작은 수를 K 와 비교하지 않았기 때문에 오류가 생김, 밑의 코드는 pushpop을 통해 결과 값을 넣고, 넣었을 때 최소값을 다시 뽑아옴 -> 비교 연산자 오류

총 100/100

import heapq
def solution(scoville, K):
    answer = 0
    heapq.heapify(scoville)
    a = heapq.heappop(scoville)

    while len(scoville) > 0:
        b = heapq.heappop(scoville)
        a = heapq.heappushpop(scoville, a + b + b)
        if a >= K:
            return answer + 1
        answer += 1

    return -1

others

import heapq
def solution(scoville, K):
    answer = 0
    heapq.heapify(scoville)
        
    while hq[0]<K:
        try :
            heapq.heappush(hq,heapq.heappop(scoville) + (heapq.heappop(scoville) * 2))
            answer +=1
        except IndexError:
            return -1

    return answer
  • index error 예외처리를 통해 더이상 2개의 종류를 pop 할 수 없을 때 -1 처리가 인상적
  • heap 자동 정렬처리가 굉장히 빠르게 됨, 그러나 여기선 a + b*2 가 되는 값이 무조건 hq 안의 값보다 커지므로 heapque가 아닌 queue로 구현해도 무방할 듯
profile
바스락바스락

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN