Programming language/Python
[python] heapq(νν, μ°μ μμν)
deo2kim
2020. 8. 26. 20:26
λ°μν
πheapqλ?
κ°λ¨νκ² λ¦¬μ€νΈλ΄μμ κ°μ₯ μμ κ°μ΄ 맨μ²μμμΉ(μΈλ±μ€ 0)μ μ€κ² ν΄μ£Όλ λ΄μ₯ λͺ¨λ
μ°μ μμ νλΌκ³ μλ©΄ μ½λ€.
π΅ μμνκΈ°
import heapq
π΅ μ μΈνκΈ°
λ³΄ν΅ λ¦¬μ€νΈλ₯Ό μ μΈνλ κ²μ²λΌ λ§λ λ€.
heap_list = []
π΅ μμ μΆκ°νκΈ° ( heapq.heappush(리μ€νΈ, κ° ))
- μλ 보μ΄λ κ² μ²λΌ κ°μ₯ μμ κ°μ΄ 맨 μ²μ μμΉμ μλ€.
μκ°λ³΅μ‘λ O(logn)
heapq.heappush(heap_list, 5)
heapq.heappush(heap_list, 10)
heapq.heappush(heap_list, 99)
heapq.heappush(heap_list, 2)
print(heap_list) # [2, 5, 99, 10]
π΅ μμ μμ νκΈ° ( heapq.heappop(리μ€νΈ) )
- μ μΌ μ²μμ μλ κ°μ΄ μμ λλ©΄μ κ·Έ κ°μ 리ν΄νλ€. κ°μ μμ νκ³ λ€μ μΆλ ₯ν΄λ³΄λ νμ΄ μ λ ¬ λμ΄ μλ€.
μκ°λ³΅μ‘λ O(logn)
print(heapq.heappop(heap_list)) # [2, 5, 99, 10]
print(heap_list) # [5, 10, 99]
a = heapq.heappop(heap_list)
print(a) # 5
π΅ κΈ°μ‘΄μ 리μ€νΈλ₯Ό νμΌλ‘ λ³ννκΈ° ( heapq.heapify(리μ€νΈ) )
μκ°λ³΅μ‘λ O(n)
ano_list = [9, 8, 7, 6, 5, 4, 1, 2, 5]
heapq.heapify(ano_list)
print(ano_list) # [1, 2, 4, 5, 5, 9, 7, 6, 8]
π΅ μ΅λκ° κ΅¬νκΈ°! (μμ©)
- κ°λ€μ νν ννλ‘ λ£μ΄μ€λ€. ννννλ‘ λ£μ΄μ£Όλ©΄ ννμ 0λ²μ§Έ μΈλ±μ€λ₯Ό κΈ°μ€μΌλ‘ νμ λ ¬μ΄ λλ€.
numbers = [1,5,9,3,7,6,4,2,8]
max_list = []
for number in numbers:
heapq.heappush(max_list, (-number, number)) # ( μ°μ μμ, -λ₯Ό λΆμ΄λ©΄ κ°μ₯ ν° κ°μ΄ κ°μ₯ μμμ§λ€. μ€μ κ°)
while max_list:
print(heapq.heappop(max_list)[1])
λ°μν