logo

Python의 힙 큐(또는 heapq)

파이썬.

간단한 힙 만들기

그만큼 힙파이(반복 가능) :- 이 기능은 다음과 같은 용도로 사용됩니다. 반복 가능한 항목을 힙으로 변환 데이터 구조. 즉, 힙 순서입니다.



파이썬3






# importing 'heapq' to implement heap queue> import> heapq> # initializing list> li>=> [>5>,>7>,>9>,>1>,>3>]> # using heapify to convert list into heap> heapq.heapify(li)> # printing created heap> print> (>'The created heap is : '>,(>list>(li)))>



>

>

검색 엔진 및 예제
산출

The created heap is : [1, 3, 9, 7, 5]>

항목을 효율적으로 추가하고 표시하기

    heappush(heap, ele) : 이 함수는 인수에 언급된 요소를 힙에 삽입하는 데 사용됩니다. 그만큼 순서가 조정되어 힙 구조가 유지됩니다. heappop(heap) : 이 함수는 힙에서 가장 작은 요소를 제거하고 반환하는 데 사용됩니다. 순서가 조정되어 힙 구조가 유지됩니다.

파이썬3




# importing 'heapq' to implement heap queue> import> heapq> # initializing list> li>=> [>5>,>7>,>9>,>1>,>3>]> # using heapify to convert list into heap> heapq.heapify(li)> # printing created heap> print>(>'The created heap is : '>, end>=>'')> print>(>list>(li))> # using heappush() to push elements into heap> # pushes 4> heapq.heappush(li,>4>)> # printing modified heap> print>(>'The modified heap after push is : '>, end>=>'')> print>(>list>(li))> # using heappop() to pop smallest element> print>(>'The popped and smallest element is : '>, end>=>'')> print>(heapq.heappop(li))>

>

>

산출

The created heap is : [1, 3, 9, 7, 5] The modified heap after push is : [1, 3, 4, 7, 5, 9] The popped and smallest element is : 1>

추가 및 팝핑 동시에

    heappushpop(heap, ele) :- 이 함수는 푸시 및 팝 작업의 기능을 하나의 문으로 결합하여 효율성을 높입니다. 이 작업 후에도 힙 순서가 유지됩니다. heapreplace(heap, ele) :- 이 함수도 하나의 명령문에 요소를 삽입하고 팝하지만 위 함수와는 다릅니다. 여기서는 요소가 먼저 팝된 다음 요소가 푸시됩니다. 즉, 푸시된 값보다 큰 값이 반환될 수 있습니다. heapreplace()는 heappushpop()과 달리 푸시된 요소에 관계없이 원래 힙에 있는 가장 작은 값을 반환합니다.

파이썬3




# importing 'heapq' to implement heap queue> import> heapq> # initializing list 1> li1>=> [>5>,>1>,>9>,>4>,>3>]> # initializing list 2> li2>=> [>5>,>7>,>9>,>4>,>3>]> # using heapify() to convert list into heap> heapq.heapify(li1)> heapq.heapify(li2)> # using heappushpop() to push and pop items simultaneously> # pops 2> print>(>'The popped item using heappushpop() is : '>, end>=>'')> print>(heapq.heappushpop(li1,>2>))> # using heapreplace() to push and pop items simultaneously> # pops 3> print>(>'The popped item using heapreplace() is : '>, end>=>'')> print>(heapq.heapreplace(li2,>2>))>

>

>

산출

The popped item using heappushpop() is : 1 The popped item using heapreplace() is : 3>

Python의 힙에서 가장 큰 요소와 가장 작은 요소 찾기

    nlargest(k, iterable, key = fun) : 이 함수는 지정된 iterable에서 k개의 가장 큰 요소를 반환하고 언급된 경우 키를 충족하는 데 사용됩니다. nsmallest(k, iterable, key = fun) : 이 함수는 지정된 iterable에서 k개의 가장 작은 요소를 반환하고 언급된 경우 키를 충족하는 데 사용됩니다.

파이썬3




# Python code to demonstrate working of> # nlargest() and nsmallest()> # importing 'heapq' to implement heap queue> import> heapq> # initializing list> li1>=> [>6>,>7>,>9>,>4>,>3>,>5>,>8>,>10>,>1>]> # using heapify() to convert list into heap> heapq.heapify(li1)> # using nlargest to print 3 largest numbers> # prints 10, 9 and 8> print>(>'The 3 largest numbers in list are : '>, end>=>'')> print>(heapq.nlargest(>3>, li1))> # using nsmallest to print 3 smallest numbers> # prints 1, 3 and 4> print>(>'The 3 smallest numbers in list are : '>, end>=>'')> print>(heapq.nsmallest(>3>, li1))>

>

>

산출

The 3 largest numbers in list are : [10, 9, 8] The 3 smallest numbers in list are : [1, 3, 4]>

예:

파이썬3


벨포드 알고리즘



import> heapq> # Initialize a list with some values> values>=> [>5>,>1>,>3>,>7>,>4>,>2>]> # Convert the list into a heap> heapq.heapify(values)> # Print the heap> print>(>'Heap:'>, values)> # Add a new value to the heap> heapq.heappush(values,>6>)> # Print the updated heap> print>(>'Heap after push:'>, values)> # Remove and return the smallest element from the heap> smallest>=> heapq.heappop(values)> # Print the smallest element and the updated heap> print>(>'Smallest element:'>, smallest)> print>(>'Heap after pop:'>, values)> # Get the n smallest elements from the heap> n_smallest>=> heapq.nsmallest(>3>, values)> # Print the n smallest elements> print>(>'Smallest 3 elements:'>, n_smallest)> # Get the n largest elements from the heap> n_largest>=> heapq.nlargest(>2>, values)> # Print the n largest elements> print>(>'Largest 2 elements:'>, n_largest)>

>

>

산출

Heap: [1, 4, 2, 7, 5, 3] Heap after push: [1, 4, 2, 7, 5, 3, 6] Smallest element: 1 Heap after pop: [2, 4, 3, 7, 5, 6] Smallest 3 elements: [2, 3, 4] Largest 2 elements: [7, 6]>

이 프로그램은 Python의 heapq 모듈을 사용하여 힙 큐를 생성하고 목록을 힙으로 변환, 힙에 새 값 추가, 힙에서 가장 작은 요소 제거, 힙에서 n 개의 가장 작은 요소 및 n 개의 가장 큰 요소 가져오기 등 다양한 작업을 수행합니다. 힙.

메모 Python의 heapq 모듈은 힙에 대한 별도의 데이터 구조를 생성하지 않고 목록에서 힙 작업을 수행하는 기능을 제공합니다. heapq 모듈은 효율적이고 사용하기 쉬우므로 Python에서 우선순위 큐 및 기타 데이터 구조를 구현하는 데 널리 사용됩니다.

Python에서 힙 큐(또는 heapq)를 사용하면 다음과 같은 이점이 있습니다.

    효율성: 힙 큐는 Python에서 우선순위 큐와 힙을 관리하기 위한 매우 효율적인 데이터 구조입니다. 많은 작업에 대수적 시간 복잡성을 제공하므로 많은 응용 프로그램에서 널리 사용됩니다. 공간 효율적 : 힙 큐는 요소를 배열 기반 표현으로 저장하여 연결된 목록과 같은 노드 기반 데이터 구조와 관련된 오버헤드를 최소화하므로 공간 효율적입니다. 사용하기 쉬움 : Python의 힙 큐는 힙에서 요소 삽입, 삭제, 검색과 같은 기본 작업을 쉽게 수행할 수 있게 해주는 간단하고 직관적인 API를 통해 사용하기 쉽습니다. 유연성: Python의 힙 큐는 우선순위 큐, 힙, 이진 트리와 같은 다양한 데이터 구조를 구현하는 데 사용할 수 있으므로 많은 애플리케이션을 위한 다목적 도구가 됩니다.

Python에서 힙 큐(또는 heapq)를 사용할 때의 단점:

    제한된 기능: 힙 큐는 주로 우선순위 큐 및 힙을 관리하기 위해 설계되었으며 더 복잡한 데이터 구조 및 알고리즘에는 적합하지 않을 수 있습니다. 무작위 액세스 없음: 힙 큐는 요소에 대한 무작위 액세스를 지원하지 않으므로 힙 중간에 있는 요소에 액세스하거나 힙 상단에 없는 요소를 수정하는 것이 어렵습니다. 정렬 없음: 힙 큐는 정렬을 지원하지 않으므로 특정 순서로 요소를 정렬해야 하는 경우 다른 데이터 구조나 알고리즘을 사용해야 합니다. 스레드로부터 안전하지 않음: 힙 큐는 스레드로부터 안전하지 않습니다. 즉, 데이터 동기화가 중요한 다중 스레드 애플리케이션에 사용하기에 적합하지 않을 수 있습니다.

전반적으로 힙 큐는 Python에서 우선 순위 큐와 힙을 관리하기 위한 매우 효율적이고 유연한 데이터 구조이지만 기능이 제한적일 수 있으며 모든 애플리케이션에 적합하지 않을 수 있습니다.