def TestBuildMinHeap(self):
     input = [random.randrange(100) for _ in range(100)]
     h = Heap(input)
     sorted_input = sorted(input)
     for i in range(len(input)):
         self.assertEqual(h.peek_min(), sorted_input[i])
         self.assertEqual(h.extract_min(), sorted_input[i])
 def TestMinHeapWithTuples(self):
     input = [(random.randrange(100), "Hullo!") for _ in range(100)]
     h = Heap(key=lambda x: x[0])
     for num in input:
         h.insert(num)
     sorted_input = sorted(input)
     for i in range(len(input)):
         self.assertEqual(h.extract_min(), sorted_input[i])
 def TestMinHeapWithRandomInput(self):
     input = [random.randrange(100) for _ in range(100)]
     h = Heap()
     for num in input:
         h.insert(num)
     sorted_input = sorted(input)
     for i in range(len(input)):
         self.assertEqual(h.extract_min(), sorted_input[i])
 def TestSizeReducedAfterExtractMin(self):
     input = [6, 1, 4, 5, 3, 2]
     h = Heap()
     for num in input:
         h.insert(num)
     initial_size = h.size
     self.assertEqual(initial_size, len(h.a))
     h.extract_min()
     self.assertEqual(initial_size - 1, h.size)
Beispiel #5
0
def construct_tree(freqs):
	# constructs the tree given the frequencies of each character
	nodes = [HuffmanNode(letter, freqs[letter]) for letter in freqs]
	# nodes contains the HuffmanNodes
	trees = [HuffmanTree(node) for node in nodes]
	h = Heap()
	for tree in trees:
		h.insert(tree) # the heap contains all the trees
	while len(h.elems) > 2: # including 0
		t1 = h.minimum() # extract the two least frequent letters
		h.delete()
		t2 = h.minimum()
		h.delete()
		newTree = combine(t2, t1) # create a new tree combining the two nodes
		h.insert(newTree) # insert the new tree back into the heap
	# at this point, the heap contains only one element
	return h.minimum()	
 def TestMinHeapProperty(self):
     input = [6, 1, 4, 5, 3, 2]
     h = Heap()
     for num in input:
         h.insert(num)
     self.assertEqual(h.extract_min(), 1)
"""Test driver to confirm build_heap method runs in O(n) time"""

import random
import time

from heaps import Heap

inputs = []
for x in range(1, 10):
    inputs.append([random.randrange(10000) for _ in range(x * 100000)])

for i, input in enumerate(inputs):
    start = time.time()
    Heap(input)
    ellapsed = time.time() - start
    print("Took {} seconds to build a heap from {}00,000 "
          "elements".format(ellapsed, i + 1))