Python에서 heapq 모듈을 사용하는 방법
heapq 모듈은 힙 알고리즘을 제공합니다. heapq는 자식 노드와 부모 노드가 정렬되어 있는 트리 데이터 구조입니다. 이 모듈은 heap[k]
힙 q 유형 인쇄
import math import random from cStringIO import StringIO def show_tree(tree, total_width=36, fill=' '): output = StringIO() last_row = -1 for i, n in enumerate(tree): if i: row = int(math.floor(math.log(i+1, 2))) else: row = 0 if row != last_row: output.write('\n') columns = 2**row col_width = int(math.floor((total_width * 1.0) / columns)) output.write(str(n).center(col_width, fill)) last_row = row print output.getvalue() print '-' * total_width print return data = random.sample(range(1,8), 7) print 'data: ', data show_tree(data)
결과 인쇄
data: [3, 2, 6, 5, 4, 7, 1] 3 2 6 5 4 7 1 ------------------------- heapq.heappush(heap, item)
요소를 힙에 푸시하고 위 코드를 수정
heap = [] data = random.sample(range(1,8), 7) print 'data: ', data for i in data: print 'add %3d:' % i heapq.heappush(heap, i) show_tree(heap)
결과 인쇄
data: [6, 1, 5, 4, 3, 7, 2] add 6: 6 ------------------------------------ add 1: 1 6 ------------------------------------ add 5: 1 6 5 ------------------------------------ add 4: 1 4 5 6 ------------------------------------ add 3: 1 3 5 6 4 ------------------------------------ add 7: 1 3 5 6 4 7 ------------------------------------ add 2: 1 3 2 6 4 7 5 ------------------------------------
결과에 따르면, 자식 노드의 요소가 부모 노드의 요소보다 크다는 것을 알 수 있습니다. 형제 노드는 정렬되지 않습니다.
heapq.heapify(list)
목록 유형을 힙으로 변환하고 목록을 선형 시간으로 재정렬합니다.
print 'data: ', data heapq.heapify(data) print 'data: ', data show_tree(data)
결과 인쇄
data: [2, 7, 4, 3, 6, 5, 1] data: [1, 3, 2, 7, 6, 5, 4] 1 3 2 7 6 5 4 ------------------------------------ heapq.heappop(heap)
힙에서 가장 작은 요소를 제거하고 반환합니다. heapify() 및 heappop()을 사용하여 정렬합니다.
data = random.sample(range(1, 8), 7) print 'data: ', data heapq.heapify(data) show_tree(data) heap = [] while data: i = heapq.heappop(data) print 'pop %3d:' % i show_tree(data) heap.append(i) print 'heap: ', heap
결과 인쇄
data: [4, 1, 3, 7, 5, 6, 2] 1 4 2 7 5 6 3 ------------------------------------ pop 1: 2 4 3 7 5 6 ------------------------------------ pop 2: 3 4 6 7 5 ------------------------------------ pop 3: 4 5 6 7 ------------------------------------ pop 4: 5 7 6 ------------------------------------ pop 5: 6 7 ------------------------------------ pop 6: 7 ------------------------------------ pop 7: ------------------------------------ heap: [1, 2, 3, 4, 5, 6, 7]
정렬된 힙을 볼 수 있습니다.
heapq.heapreplace(iterable, n)
기존 요소를 제거하고 새 값으로 바꿉니다.
data = random.sample(range(1, 8), 7) print 'data: ', data heapq.heapify(data) show_tree(data) for n in [8, 9, 10]: smallest = heapq.heapreplace(data, n) print 'replace %2d with %2d:' % (smallest, n) show_tree(data)
결과 인쇄
data: [7, 5, 4, 2, 6, 3, 1] 1 2 3 5 6 7 4 ------------------------------------ replace 1 with 8: 2 5 3 8 6 7 4 ------------------------------------ replace 2 with 9: 3 5 4 8 6 7 9 ------------------------------------ replace 3 with 10: 4 5 7 8 6 10 9 ------------------------------------
heapq.nlargest(n, iterable ) 및 heapq.nsmallest(n, iterable)
n개의 최대값과 최소값을 목록에 반환
data = range(1,6) l = heapq.nlargest(3, data) print l # [5, 4, 3] s = heapq.nsmallest(3, data) print s # [1, 2, 3]
PS: 계산 문제
요소 수 K=5로 최소 힙 코드 예제 구성:
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: kentzhan # import heapq import random heap = [] heapq.heapify(heap) for i in range(15): item = random.randint(10, 100) print "comeing ", item, if len(heap) >= 5: top_item = heap[0] # smallest in heap if top_item < item: # min heap top_item = heapq.heappop(heap) print "pop", top_item, heapq.heappush(heap, item) print "push", item, else: heapq.heappush(heap, item) print "push", item, pass print heap pass print heap print "sort" heap.sort() print heap
결과:
Python에서 heapq 모듈 사용과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

Linux 터미널에서 Python 사용 ...

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.
