Exemple #1
0
 def test_key_function(self):
     fruits = ['Watermelon', 'blueberry', 'lime', 'Lemon', 'pear', 'loquat']
     fruits_heap = MinHeap(fruits, key=str.lower)
     self.assertEqual(fruits_heap.peek(), 'blueberry')
     fruits_heap.push('Apple')
     fruits_heap.push('jujube')
     self.assertEqual(fruits_heap.pop(), 'Apple')
     self.assertEqual(fruits_heap.pop(), 'blueberry')
     self.assertEqual(fruits_heap.pop(), 'jujube')
     self.assertEqual(fruits_heap.pop(), 'Lemon')
Exemple #2
0
 def test_pop(self):
     item_0 = {"id":1, "price":1.0}
     item_1 = {"id":2, "price":2.0}
     item_2 = {"id":3, "price":.0}
     heap = MinHeap()
     heap.push(item_0)
     heap.push(item_1)
     heap.push(item_2)
     self.assertEqual(heap.pop(), item_2)
     self.assertEqual(heap.pop(), item_0)
     self.assertEqual(heap.pop(), item_1)
Exemple #3
0
def a_star_search(init_state , target_state) :
    heap = MinHeap()
    heap.push(init_state)
    print '++++++++++++++'
    cnt = 0
    while True :
        if heap.empty() :
            return None
        cnt += 1
        cur_state = heap.pop()
        if cur_state.is_same2other_state(target_state) :
            return cur_state
        states_lst = cur_state.expand_states()
        for state in states_lst : 
            state.set_cost4a_star(target_state)
            if not heap.has_same(state , Puzzle8State.is_2puzzle_same) :
                heap.push(state)
        if cnt%1000 == 0 :
            print "state {0} has been searched , currently heap has {1} states .".format(cnt , heap.size())
Exemple #4
0
    def split(self, x, y):
        """Find (n_class-1) best thresholds for a feature x and corresponding labels y.

        Args:
            x: a feature.
            y: the labels.

        Returns:
            a list of the best thresholds(x-value).
        """
        heap = MinHeap(self.n_class)
        sort_index = sorted(range(len(x)), key=lambda i: x[i])
        x_sort = x[sort_index]
        y_sort = y[sort_index]
        thres_i, ig = self.split_by_entropy(x_sort, y_sort, sort=False)
        heap.push((tuple(range(len(y))), thres_i), -ig)
        while heap.size < self.n_class and heap.minimum() < 0:
            (piece, thres), ig = heap.pop()
            piece1, piece2 = list(piece[:thres]), list(piece[thres:])
            thres_i1, ig1 = self.split_by_entropy(x_sort[piece1], y_sort[piece1], sort=False)
            thres_i2, ig2 = self.split_by_entropy(x_sort[piece2], y_sort[piece2], sort=False)
            heap.push((piece1, thres_i1), -ig1)
            heap.push((piece2, thres_i2), -ig2)
        return x_sort[sorted([item[0][0][-1] for item in heap.items()])[:-1]]
Exemple #5
0
 def test_push_onto_heap(self):
     numbers = [11, 322, 3, 199, 29, 7, 1, 18, 76, 4, 2, 47, 123]
     i = MinHeap(BIG_NUMBERS)
     i.push(17)
     self.assertEqual(i.peek(), 17)
     i.push(24)
     self.assertEqual(i.pop(), 17)
     self.assertEqual(i.pop(), 24)
     self.assertEqual(i.pop(), 46)
     h = MinHeap(numbers)
     h.push(6)
     self.assertEqual(len(h), len(numbers)+1)
     self.assertEqual(h.pop(), 1)
     self.assertEqual(h.pop(), 2)
     self.assertEqual(h.pop(), 3)
     self.assertEqual(h.pop(), 4)
     self.assertEqual(h.pop(), 6)
Exemple #6
0
class MinHeapTest(unittest.TestCase):

	@classmethod
	def setUpClass(self):
		self.H = MinHeap()
		self.data = [('A',7),('B',3),('C',4),('D',1),('E',6),('F',5),('G',2)]

	@classmethod
	def tearDownClass(self):
		self.H = None

	def check_assertions(self,heap_val,data_val,size_val):
		self.assertEqual(self.H.heap,heap_val,'Non-Empty Heap')
		self.assertEqual(self.H.data,data_val,'Non-Empty Data')
		self.assertEqual(self.H.size,size_val,'Non-Zero Size')

	def test_empty_heap_1_func(self):
		self.H.emptyHeap()
		self.check_assertions([],{},0)

	def test_empty_heap_2_pop(self):
		self.assertRaises(Exception,self.H.pop)

	def test_empty_heap_3_find(self):
		self.assertRaises(Exception,self.H.find,'A')

	def test_empty_heap_4_peek(self):
		self.assertRaises(Exception,self.H.peek)

	def test_empty_heap_5_heapify(self):
		self.H.heapify()
		self.check_assertions([],{},0)

	def test_empty_heap_6_update(self):
		self.assertRaises(Exception,self.H.update,'A',3)

	def test_single_entry_heap_1_push(self):
		self.H.emptyHeap()
		self.H.push('A',3)
		self.check_assertions([('A',[3])],{'A':[[3],0]},1)

	def test_single_entry_heap_2_find(self):
		self.assertEqual(self.H.find('A'),3)
		self.assertRaises(Exception,self.H.find,'B')

	def test_single_entry_heap_3_peek(self):
		self.assertEqual(self.H.peek(),('A',3))

	def test_single_entry_heap_4_heapify(self):
		self.H.heapify()
		self.check_assertions([('A',[3])],{'A':[[3],0]},1)

	def test_single_entry_heap_5_update(self):
		self.H.update('A',7)
		self.check_assertions([('A',[7])],{'A':[[7],0]},1)

	def test_single_entry_heap_6_pop(self):
		self.assertEqual(self.H.pop(),('A',7))
		self.check_assertions([],{},0)

	def check_heap_order_property(self):
		N = self.H.size
		for k in range(N):
			x,y = self.H.heap[k]
			self.assertEqual(self.H.data[x],[y,k])
			childOne,childTwo,parent = 2*k+1,2*k+2,(k-1)//2
			if parent >= 0: 
				p = self.H.heap[parent]
				self.assertGreater(y,p[1])
				self.assertEqual(self.H.data[p[0]],[p[1],parent])
			if childOne < N:
				c = self.H.heap[childOne]
				self.assertLess(y,c[1])
				self.assertEqual(self.H.data[c[0]],[c[1],childOne])
			if childTwo < N:
				c = self.H.heap[childTwo]
				self.assertLess(y,c[1])
				self.assertEqual(self.H.data[c[0]],[c[1],childTwo])


	def test_multiple_entry_heap_1_push(self):
		self.H.emptyHeap()
		for k,v in self.data:
			self.H.push(k,v)
			self.check_heap_order_property()

	def test_multiple_entry_heap_2_peek(self):
		self.assertEqual(self.H.peek(),('D',1))

	def test_multiple_entry_heap_3_find(self):
		for k,v in self.data:
			self.assertEqual(self.H.find(k),v)

	def test_multiple_entry_heap_4_heapify(self):
		values = self.H.data.values()
		self.H.heapify()
		self.assertEqual(values,self.H.data.values())

	def test_multiple_entry_heap_5_update(self):
		self.H.update('G',8)
		self.check_heap_order_property()
		self.H.update('E',0)
		self.check_heap_order_property()
		self.H.update('E',9)
		self.check_heap_order_property()
		self.H.update('F',2)
		self.check_heap_order_property()
		self.H.update('G',2)
		self.H.update('E',6)
		self.H.update('F',5)
		self.check_heap_order_property()

	def test_multiple_entry_heap_6_pop(self):	
		heap_sorted = []
		while not self.H.isEmpty():
			heap_sorted.append(self.H.pop())
		self.assertEqual(heap_sorted,sorted(self.data,key=lambda (x,y): y))
		self.check_assertions([],{},0)
Exemple #7
0
 def test_peek(self):
     item = {"id":1, "price":1.0}
     heap = MinHeap()
     heap.push(item)
     self.assertEqual(heap.peek(), item)
Exemple #8
0
 def test_faster_than_sorting(self):
     with Timer() as sort_timer:
         sorted(MANY_BIG_NUMBERS)
     heap = MinHeap(MANY_BIG_NUMBERS)
     with Timer() as min_heap_timer:
         heap.push(150)
         heap.push(950)
         heap.push(400)
         heap.push(760)
         heap.push(280)
         heap.push(870)
         heap.push(330)
         heap.push(1000)
         heap.push(50)
         heap.push(500)
         items = [heap.pop() for _ in range(10)]
     self.assertEqual(len(items), 10)
     self.assertLess(min_heap_timer.elapsed, sort_timer.elapsed)