Ejemplo n.º 1
0
def main():
    """test"""

    test = [6, 5, 3, 1, 8, 7, 2, 4]
    heap = list_to_min_heap(test)
    show_tree(heap)
    heapq.heapify(test)
    show_tree(test)
    print test
Ejemplo n.º 2
0
def main():
    """test"""

    test = [6, 5, 3, 1, 8, 7, 2, 4]
    heap = list_to_min_heap(test)
    show_tree(heap)
    heapq.heapify(test)
    show_tree(test)
    print test
def main():
    heapq.heapify(data)
    print("start ")
    show_tree(data)

    for n in [0, 13]:
        smallest = heapq.heapreplace(data, n)
        print(f"replace {smallest:>2} with {n:>2}:")
        show_tree(data)
Ejemplo n.º 4
0
def main():
    heap = []
    print("random :", data)
    print()

    for n in data:
        print(f"add {n:3}")
        heapq.heappush(heap, n)
        show_tree(heap)
def main():
    print("random    :", data)
    heapq.heapify(data)
    print("heapified :")
    show_tree(data)
    print

    for i in range(2):
        smallest = heapq.heappop(data)
        print(f"pop    {smallest:>3}:")
        show_tree(data)
Ejemplo n.º 6
0
def main():
    """test"""

    test = [6, 5, 3, 1, 8, 7, 2, 4]
    heap = list_to_heap(test, 'min')
    show_tree(heap)
    heapq.heapify(test)
    show_tree(test)
    print heap
    print test
    print heap_sort(test, 'max')
    print heap_sort(test, 'min')
Ejemplo n.º 7
0
import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data

heapq.heapify(data)
print 'start:'
show_tree(data)

for n in [0, 13]:
    smallest = heapq.heapreplace(data, n)
    print 'replace %2d with %2d:' % (smallest, n)
    show_tree(data)
Ejemplo n.º 8
0
        # child node has value larger than parent
        if A[MaxChildIndex] > A[ParentIndex]:
            swap(A, MaxChildIndex, ParentIndex)
            # move down to largest child
            ParentIndex = MaxChildIndex
            MaxChildIndex = 2 * ParentIndex + 1
        else:
            #parent node has value greater than child node
            #no need to percolate down - heapify on linear time!
            return  # force exit


def swap(A, x, y):
    temp = A[x]
    A[x] = A[y]
    A[y] = temp


A = [15, 34, 111, 22, 63, 12, 77, 55, 2]
print(A, "changed to heap >>> ", end="")
BuildMaxHeap(A)
print(A)

#Print Heap
import sys

sys.path.append("./mylib")
from heapq_showtree import show_tree

show_tree(A)
Ejemplo n.º 9
0
import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data

heap = []
print('random: ', data)
print()

for n in data:
    print('add {:>3}:'.format(n))
    heapq.heappush(heap, n)
    show_tree(heap)

def main():
    print("random    :", data)
    heapq.heapify(data)
    print("heapified :")
    show_tree(data)
    print(data)
Ejemplo n.º 11
0
    result = []
    for origin, cur_file in enumerate(ls_of_filedata):
        if cur_file:
            heappush(min_heap, (cur_file[0], origin, 1))

    while min_heap:
        nxt_min, origin, nxt_ndx = heappop(min_heap)
        result.append(nxt_min)
        nxt_file = ls_of_filedata[origin]
        if nxt_ndx < len(nxt_file):
            heappush(min_heap, (nxt_file[nxt_ndx], origin, nxt_ndx + 1))
    return result

    return min_heap

if __name__ == '__main__':
    test_cases = [
        ([[1, 2], [2, 3, 4, 5]], [1, 2, 2, 3, 4, 5]),
        ([[1, 2], [2, 3, 4, 5], [3, 4, 5]], [1, 2, 2, 3, 3, 4, 4, 5, 5]),

    ]
    for test_case, exp in test_cases:
        show_tree(merge_sorted_file(test_case))
        print(merge_sorted_file(test_case)) == exp






Ejemplo n.º 12
0
    # right child exists and is value of right child larger than left child
    if (MaxChildIndex < Size) and (A[MaxChildIndex] < A[MaxChildIndex + 1]):
        MaxChildIndex += 1
    # child node has value larger than parent
    if A[MaxChildIndex] > A[ParentIndex]:
        swap(A, MaxChildIndex, ParentIndex)
        # move down to largest child
        ParentIndex = MaxChildIndex
        MaxChildIndex = 2 * ParentIndex + 1
    else:
        #parent node has value greater than child node
        #no need to percolate down - heapify on linear time!
        return  # force exit
  
def swap(A, x, y):
  temp = A[x]
  A[x] = A[y]
  A[y] = temp


A = [ 15,34,111,22,63,12,77,55,2]
print(A, "changed to heap >>> ", end="")
BuildMaxHeap(A)        
print(A)

#Print Heap
import sys
sys.path.append("./mylib")
from heapq_showtree import show_tree
show_tree(A)
Ejemplo n.º 13
0
# -*- coding: utf-8 -*-
#2.3 heapq模块实现了一个适用于Python列表的最小堆排序算法。
import heapq
from heapq_heapdata import data
from heapq_showtree import show_tree
#2.3.2创建堆,创建堆有两种基本方式:heappush()和heapify()
#使用heappush()中,从数据源增加新元素时会保持元素的堆顺序
heap = []
print 'random :', data
print
for n in data:
    print 'add %3d:' % n
    heapq.heappush(heap, n)
    show_tree(heap)
#如果数据已经在内存中,使用heaoify()原地重新组织列表中的元素会更高效
from heapq_heapdata import data
print 'random    :', data
heapq.heapify(data)
print 'heapified :'
show_tree(data)
print
#2.3.3访问堆的内容
#一旦堆已正确组织,就可以使用heappop()删除最小值的元素
from heapq_heapdata import data
heapq.heapify(data)
print 'heapified :'
show_tree(data)
print
for i in xrange(2):
    smallest = heapq.heappop(data)
    print 'pop              %3d:' % smallest
Ejemplo n.º 14
0
#Source: https://github.com/careermonk/DataStructureAndAlgorithmicThinkingWithPython/blob/master/src/chapter07priorityqueues/KthSmallestWithExtraHeap.py

import sys
sys.path.append("./mylib")
import Heap  #custom Heap module
from heapq_showtree import show_tree #custom module for printing Heap

#Initialize Max Heap
Something = Heap.MaxHeap()

#Insert into Heap
Something.Insert(13)
Something.Insert(5)
Something.Insert(6)
Something.Insert(1)
Something.Insert(2)
Something.Insert(4)
Something.Insert(17)

#Print Heap - linear
Something.printHeap()
#Print Heap - tree type
show_tree(Something.printHeap2())

#Delete node
for x in range (1,Something.size+1):
    print("Delete node")
    Something.Delete()
    show_tree(Something.printHeap2())
Ejemplo n.º 15
0
import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data

print 'random    :', data
heapq.heapify(data)
print 'heapified :'
show_tree(data)
print

for i in xrange(2):
    smallest = heapq.heappop(data)
    print 'pop    %3d:' % smallest
    show_tree(data)
Ejemplo n.º 16
0
import heapq
from heapq_showtree import show_tree


class Node:
    def __init__(self, data):
        self.data = data
        self.right = None
        self.left = None

    def PrintTree(self):
        print(self.data)


ls = [int(n) for n in input("Enter the Max heap").split()]
k = int(input("Enter the Value of K"))
h = []
print(heapq.nlargest(k, ls))
show_tree(ls)
Ejemplo n.º 17
0
# heapq_heappush.py

import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data

heap = []
print('casuali :', data)
print()

for n in data:
    print('aggiungo {:>3}:'.format(n))
    heapq.heappush(heap, n)
    show_tree(heap)
Ejemplo n.º 18
0
# -*- coding: utf-8 -*-	
#2.3 heapq模块实现了一个适用于Python列表的最小堆排序算法。
import heapq
from heapq_heapdata import data
from heapq_showtree import show_tree
#2.3.2创建堆,创建堆有两种基本方式:heappush()和heapify()
#使用heappush()中,从数据源增加新元素时会保持元素的堆顺序
heap = []
print 'random :', data
print
for n in data:
	print 'add %3d:' % n
	heapq.heappush(heap, n)
	show_tree(heap)
#如果数据已经在内存中,使用heaoify()原地重新组织列表中的元素会更高效
from heapq_heapdata import data
print 'random    :', data
heapq.heapify(data)
print 'heapified :'
show_tree(data)	
print
#2.3.3访问堆的内容
#一旦堆已正确组织,就可以使用heappop()删除最小值的元素
from heapq_heapdata import data
heapq.heapify(data)
print 'heapified :'
show_tree(data)
print
for i in xrange(2):
	smallest = heapq.heappop(data)
	print 'pop              %3d:' % smallest