Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- dict
- pig
- 유사도
- SPLIT
- p-value
- list
- pca
- hive
- 분산분석
- SQL on 하둡
- 하둡
- distribution
- 결정계수
- 데이터프레임
- merge
- 밀도기반
- 다중공선성
- T-검정
- 가설검정
- DBSCAN
- DataFrame
- cross validation
- k-means
- join
- Python
- Sawzall
- 병렬 쿼리 시스템
- 분포
- 딕셔너리
- 교차검증
Archives
- Today
- Total
one of a kind scene
힙(Heap)구조에 대해서 알아보자(python 내장 모듈 heapq) 본문
Heap의 특징
a = [3, 8, 5, 2]
heapq.heapify(a)
print(a)
- 원소들이 항상 정렬된 상태로 추가되고 삭제됨(binary tree 기반)
- 최소 힙(min heap)이라고 칭함
- 최소 힙은 root 즉 idx 0에 위치한 값이 가장 작고 자식들은 root보다 같거나 작음
- 즉, 최소 힙의 root는 최소값이니 이 성질을 잘 기억하자
- 따라서, 노드들도 자식들보다 같거나 작음
1. 내장모듈 heapq 불러오기
import heapq
2. heap 생성하기
- heapq 모듈을 사용하면 python의 일반 리스트를 heap 구조로 사용할 수 있게해줌
heap = []
3. 힙에 element 넣어주기 : heappush( )
heapq.heappush(heap, 6)
heapq.heappush(heap, 3)
heapq.heappush(heap, 2)
heapq.heappush(heap, 1)
print(heap)
[1, 2, 3, 6]
4. 힙에 element 넣어주기2 : heappush( )
heapq.heappush(heap, 5)
heapq.heappush(heap, 4)
heapq.heappush(heap, 8)
heapq.heappush(heap, 1)
heapq.heappush(heap, 3)
heapq.heappush(heap, 7)
print(heap)
[1, 3, 7, 5, 4, 8]
5. 힙에 element 빼내기 : heappop( )
- heappop( )을 하면 그냥 pop( )과 달리 가장 작은 값이 pop됨
print(heapq.heappop(heap))
print(heap)
1
[2, 3, 6]
6. 이미 element가 채워져있는 리스트를 heap구조로 만들기 : heapify( )
- list를 heap화 해준다고 생각하자
heap = [8, 3, 5, 2]
heapq.heapify(heap)
print(heap)
[2, 3, 5, 8]
참고 url
'Python > 내장모듈 및 자료구조' 카테고리의 다른 글
[Python] 튜플(tuple), 리스트(list), 셋(set), 딕셔너리(dict) 비교 (0) | 2020.03.25 |
---|---|
[itertools] 순열(permutations), 조합(combinations), 곱집합(product) 만들기 (0) | 2020.01.28 |
[list] split과 join 사용 (0) | 2020.01.03 |
list 다루기(정렬하기, 역순으로 배치하기, 역순으로 가져오기) (0) | 2019.12.26 |