import heapq
def solution(scoville, K):
# 힙구조 사용해도 좋을 듯
# 최소 힙 구현
heap = scoville
heapq.heapify(heap) # 힙 구조 만들어주기
answer = 0
# 반복문 한번 돌 때마다 answer += 1
while heap[0]<K:
first = heapq.heappop(heap)
second = heapq.heappop(heap)
heapq.heappush(heap, (first + second*2))
answer += 1
# 예외처리
if (len(heap) == 1) and (heap[0]<K):
answer = -1
break
return answer
import heapq
def solution(scoville, K):
heap = scoville
heapq.heapify(heap) # 힙 구조 만들어주기
count = 0
while heap[0]<K:
try:
heapq.heappush(heap, heapq.heappop(heap) + heapq.heappop(heap) * 2)
count += 1
except IndexError:
return -1
return count
예외 처리는 if를 이용한 분기보다 try ~ except를 사용하는 것이 좀 더 파이썬스럽다고 한다.
if를 이용한 예외 처리를 LBYL이라 부르고 try ~ except를 이용한 예외 처리를 EAFP라고 부른다. 파이썬은 EAFP 방식을 권장!!
해당 문제에서 힙구조가 강력한 이유는, 가장 작은 값을 차례로 연산해야 하기 때문이다.