def test_insert_empty(self): """ An empty MaxHeap stores a new value as the root. No algorithms necessary. """ h = MaxHeap() h.insert(10) self.assertEqual(10, h._data[0])
def main(): frontier = MaxHeap() goal = PlayTypeByTurn('Snake', 5) initial_state = init_state() frontier.insert((initial_state, goal.score_func(initial_state))) goal_state = None while frontier.size() > 0: best_candidate = frontier.extract() print("current candidate: " + str(best_candidate[1]) + " " + best_candidate[0].describe()) if goal.goal_func(best_candidate[0]): goal_state = best_candidate[0] break frontier.insert_list([ entry for entry in [(child, goal.score_func(child)) for child in generate_children(best_candidate[0])] if entry[1] > 0 ]) if not goal_state: print('Goal unachievable') return current = goal_state goal_to_start = [current] while current.parent: current = current.parent goal_to_start.append(current) for state in goal_to_start[::-1]: print(state.prev_action)
def main(): frontier = MaxHeap() goal = PlayTypeByTurn('Snake', 5) initial_state = init_state() frontier.insert((initial_state, goal.score_func(initial_state))) goal_state = None while frontier.size() > 0: best_candidate = frontier.extract() print("current candidate: " + str(best_candidate[1]) + " " + best_candidate[0].describe()) if goal.goal_func(best_candidate[0]): goal_state = best_candidate[0] break frontier.insert_list([entry for entry in [(child, goal.score_func(child)) for child in generate_children(best_candidate[0])] if entry[1] > 0]) if not goal_state: print('Goal unachievable') return current = goal_state goal_to_start = [current] while current.parent: current = current.parent goal_to_start.append(current) for state in goal_to_start[::-1]: print(state.prev_action)
def test_delete_one(self): """ Deleting when there is only one element removes that element and returns it. """ h = MaxHeap() h.insert(10) self.assertEqual(10, h.delete()) self.assertEqual(0, len(h._data))
def test_insert_smaller_one(self): """ An inserted value that is smaller than the root becomes the left child. """ h = MaxHeap() h.insert(10) h.insert(5) self.assertEqual(10, h._data[0]) self.assertEqual(5, h._data[1])
def test_insert_omg(self): """ Lots of inserts should result in the MaxHeap obeying the max-heap property at every node in the tree. """ h = MaxHeap() for _ in range(100): h.insert(random.randint(1, 1000)) for i in reversed(range(len(h._data))): if (i - 1) // 2 < 0: break self.assertTrue(h._data[i] <= h._data[(i - 1) // 2])
class PriorityQueue: def __init__(self): self.heap = MaxHeap() def enqueue(self, value): self.heap.insert(value) def dequeue(self): return self.heap.delete() def is_empty(self): return self.heap._size() == 0
def test_delete_two(self): """ Deleting when there are two elements in the heap removes the root element and returns it, leaving the other element in its place as the new root. Hint: There's a version of the pop method that takes an argument. """ h = MaxHeap() h.insert(10) h.insert(5) self.assertEqual(10, h.delete()) self.assertEqual(1, len(h._data)) self.assertEqual(5, h.delete()) self.assertEqual(0, len(h._data))
def test_insert_stable(self): """ An inserted value that is smaller than its parent will remain in the new leaf position. 10 10 / \ => / \ 8 4 8 4 / \ / \ 3 4 1 2 """ h = MaxHeap() h.insert(10) h.insert(8) h.insert(4) h.insert(3) h.insert(4) h.insert(1) h.insert(2) self.assertEqual(10, h._data[0]) self.assertEqual(8, h._data[1]) self.assertEqual(4, h._data[2]) self.assertEqual(3, h._data[3]) self.assertEqual(4, h._data[4]) self.assertEqual(1, h._data[5]) self.assertEqual(2, h._data[6])
def test_insert_unstable_six(self): """ An inserted value that is larger than its parent should sift up until the heap property is obeyed. 10 10 / \ => / \ 8 4 8 9 / \ / / \ / \ 1 3 2 1 3 2 4 """ h = MaxHeap() h.insert(10) h.insert(8) h.insert(4) h.insert(1) h.insert(3) h.insert(2) h.insert(9) self.assertEqual(10, h._data[0]) self.assertEqual(8, h._data[1]) self.assertEqual(9, h._data[2]) self.assertEqual(1, h._data[3]) self.assertEqual(3, h._data[4]) self.assertEqual(2, h._data[5]) self.assertEqual(4, h._data[6])
def heap_sort_one(init_list): '''堆排序1 循环未排序数组,将数组依次添加到堆中。 计算数组的个数或者获取堆的元素个数。 下标倒序循环,依次取出堆的最大值并在此下标赋值。 ''' max_heap = MaxHeap() for i in init_list: max_heap.insert(i) list_count = len(init_list) # list_count = max_heap.size() for c in range(list_count, 0, -1): init_list[c - 1] = max_heap.extract_max() return init_list
def test_insert_smaller_two(self): """ An inserted value that is smaller than the root of a two-element MaxHeap becomes the right child. 10 10 / => / \ 5 5 1 """ h = MaxHeap() h.insert(10) h.insert(5) h.insert(1) self.assertEqual(10, h._data[0]) self.assertEqual(5, h._data[1]) self.assertEqual(1, h._data[2])
def test_delete_larger_left_three(self): """ Deleting when there are three elements in the heap removes the root element and returns it, leaving the larger of the two children as the new root. 10 5 / \ => / 5 1 1 """ h = MaxHeap() h.insert(10) h.insert(5) h.insert(1) self.assertEqual(10, h.delete()) self.assertEqual(2, len(h._data)) self.assertEqual(5, h._data[0]) self.assertEqual(1, h._data[1])
def test_delete_larger_right_three(self): """ Deleting when there are three elements in the heap removes the root element and returns it, leaving the larger of the two children as the new root. 10 5 / \ => / 1 5 1 Hint: Two base cases, and one case that requires the algorithm. """ h = MaxHeap() h.insert(10) h.insert(1) h.insert(5) self.assertEqual(10, h.delete()) self.assertEqual(2, len(h._data)) self.assertEqual(5, h._data[0]) self.assertEqual(1, h._data[1])
def test_delete_omg(self): """ Lots of deletions should result in the MaxHeap obeying the max-heap property at every node in the tree, and the root always being the largest value in the tree. """ h = MaxHeap() for _ in range(100): h.insert(random.randint(1, 1000)) previous_root = h._data[0] + 1 # Seed a value larger than anything in the heap. while len(h._data) > 0: latest_root = h.delete() self.assertTrue(previous_root >= latest_root) for i in reversed(range(len(h._data))): if (i - 1) // 2 < 0: break self.assertTrue(h._data[i] <= h._data[(i - 1) // 2]) previous_root = latest_root
def test_insert_unstable_root_five(self): """ An inserted value that is larger than its parent should sift up until the heap property is obeyed. 10 15 / \ => / \ 8 4 8 10 / \ / \ / 1 3 1 3 4 """ h = MaxHeap() h.insert(10) h.insert(8) h.insert(4) h.insert(1) h.insert(3) h.insert(15) self.assertEqual(15, h._data[0]) self.assertEqual(8, h._data[1]) self.assertEqual(10, h._data[2]) self.assertEqual(1, h._data[3]) self.assertEqual(3, h._data[4]) self.assertEqual(4, h._data[5])
def test_insert_larger_two(self): """ An inserted value that is larger than the root becomes the new root, and the old root becomes the last element in the tree. 10 15 / => / \ 5 5 10 Hint: Remember, insertion is just two steps. Append the new leaf to the end, and sift that new leaf up. """ h = MaxHeap() h.insert(10) h.insert(5) h.insert(15) self.assertEqual(15, h._data[0]) self.assertEqual(5, h._data[1]) self.assertEqual(10, h._data[2])
def test_insert_unstable_three(self): """ An inserted value that is larger than its parent should sift up until the heap property is obeyed. 10 10 / \ => / \ 8 4 9 4 / 8 """ h = MaxHeap() h.insert(10) h.insert(8) h.insert(4) h.insert(9) self.assertEqual(10, h._data[0]) self.assertEqual(9, h._data[1]) self.assertEqual(4, h._data[2]) self.assertEqual(8, h._data[3])
def test_delete_larger_right_four(self): """ Deleting when there are four elements in the heap removes the root element and returns it, leaving the larger of the two children as the new root. 10 8 / \ => / \ 5 8 5 2 / 2 """ h = MaxHeap() h.insert(10) h.insert(5) h.insert(8) h.insert(2) self.assertEqual(10, h.delete()) self.assertEqual(3, len(h._data)) self.assertEqual(8, h._data[0]) self.assertEqual(5, h._data[1]) self.assertEqual(2, h._data[2])
def test_delete_larger_left_five_root(self): """ Deleting when there are five elements in the heap removes the root element and returns it, leaving the larger of the two children as the new root. The leaf that was made the new root sifts down as far as it needs to, to obey the heap property. 10 8 / \ => / \ 8 5 2 5 / \ / 2 1 1 """ h = MaxHeap() h.insert(10) h.insert(8) h.insert(5) h.insert(2) h.insert(1) self.assertEqual(10, h.delete()) self.assertEqual(4, len(h._data)) self.assertEqual(8, h._data[0]) self.assertEqual(2, h._data[1]) self.assertEqual(5, h._data[2]) self.assertEqual(1, h._data[3])
return False p = v return True p = arr[0] for v in arr[1:]: if v > p: return False p = v return True if __name__ == '__main__': a = [9, 4, 8, 6, 1, 23, 9, 91, 18, 7, 6, 10] heap = MaxHeap(len(a)) for v in a: heap.insert(v) b = [] v = heap.remove_top() while v is not None: b.append(v) v = heap.remove_top() print(b) # 原地堆排序 print(a) max_heap.heap_sort(a) print(a) a.clear()
class HeapTests(unittest.TestCase): def setUp(self): self.heap = MaxHeap() def test_heap_insert_works(self): self.heap.insert(6) self.heap.insert(8) self.heap.insert(10) self.heap.insert(9) self.heap.insert(1) self.heap.insert(9) self.heap.insert(9) self.heap.insert(5) self.assertEqual(self.heap.storage, [10, 9, 9, 6, 1, 8, 9, 5]) def test_get_max_works(self): self.heap.insert(6) self.heap.insert(8) self.heap.insert(10) self.heap.insert(9) self.heap.insert(1) self.heap.insert(9) self.heap.insert(9) self.heap.insert(5) self.assertEqual(self.heap.get_size(), 8) self.assertEqual(self.heap.get_max(), 10) def test_get_max_after_delete(self): self.heap.insert(6) self.heap.insert(8) self.heap.insert(10) self.heap.insert(9) self.heap.insert(1) self.heap.insert(9) self.heap.insert(9) self.heap.insert(5) self.heap.delete() self.assertEqual(self.heap.get_max(), 9) self.heap.delete() self.assertEqual(self.heap.get_max(), 9) self.heap.delete() self.assertEqual(self.heap.get_max(), 9) self.heap.delete() self.assertEqual(self.heap.get_max(), 8) self.heap.delete() self.assertEqual(self.heap.get_max(), 6) def test_delete_elements_in_order(self): self.heap.insert(6) self.heap.insert(7) self.heap.insert(5) self.heap.insert(8) self.heap.insert(10) self.heap.insert(1) self.heap.insert(2) self.heap.insert(5) descending_order = [] while self.heap.get_size() > 0: descending_order.append(self.heap.delete()) self.assertEqual(descending_order, [10, 8, 7, 6, 5, 5, 2, 1]) def test_bubble_up_was_called(self): self.heap._bubble_up = MagicMock() self.heap.insert(5) self.assertTrue(self.heap._bubble_up.called) def test_sift_down_was_called(self): self.heap._sift_down = MagicMock() self.heap.insert(10) self.heap.insert(11) self.heap.delete() self.assertTrue(self.heap._sift_down.called)
from max_heap import MaxHeap, Data priority_queue = MaxHeap() num_patients = 0 total_wait_time = 0 with open('data.txt') as events: for event in events: event_all_info = event.strip().split() event_type = event_all_info[0] if event_type == 'P': num_patients += 1 arrival_time = event_all_info[1] priority_score = event_all_info[2] priority_queue.insert(Data(priority_score, arrival_time)) else: attending_time = event_all_info[1] total_wait_time += float(attending_time) - float(priority_queue.remove().value) average_wait_time = total_wait_time/num_patients with open('solution.txt', 'w') as solution: solution.write(str(average_wait_time))
from max_heap import MaxHeap from min_heap import MinHeap if __name__ == '__main__': sup = MaxHeap([]) # MAX_HEAP inf = MinHeap([]) # MIN_HEAP n = 0 while True: # citesc numarul pe care vreau sa il inserez x = input("Numar: ") x = int(x) sup.insert(x) # inseram in max-heap if n % 2 == 0: if inf.heap_size > 0: # daca am elemente in minheap if sup.max() > inf.min( ): # daca radacina maxHeap-ului > radacina minHeapului # extrag radacinile si le inserez in cruce toMin = sup.pop_max() toMax = inf.pop_min() sup.insert(toMax) inf.insert(toMin) else: # daca numarul de numere e impar toMin = sup.pop_max() inf.insert(toMin) # extrag radacina maxHeap-ului si o inserez in minHeap n += 1 # crestem numarul de elemente procesate # getting the median if n % 2 == 0: print(sup.max() + inf.min()) / 2.0