def driver(): heapA = MinHeap() heapB = MinHeap() dictA = {} dictB = {} with open(sys.argv[1]) as f: n = int(f.readline().strip()) for _ in range(n): in_data = f.readline().strip().split() ip, tier, time = in_data[0], in_data[1], int(in_data[2]) if tier == "A": heapA.insert(time) if time not in dictA.keys(): dictA[time] = [] dictA[time].append(ip) elif tier == "B": heapB.insert(time) if time not in dictB.keys(): dictB[time] = [] dictB[time].append(ip) serve_requests(heapA, dictA) serve_requests(heapB, dictB)
def get_graph_from_file(filename): graph_heap = MinHeap() with open(filename, 'r') as f: for line in f: node = Node() split_line = line.split() node.g_num = int(split_line[0]) #index label keeps track of where this node is in the heap's array node.index_label = graph_heap.size for edge in split_line[1:]: target, length = edge.split(',') node.edges.append({'target':int(target), 'length':int(length)}) graph_heap.insert(node) return graph_heap
def find_path_astar(start, stop): visited = [] unvisited = [start] parent = {start: "None"} gscore = {start: 0} #fscore = {start:1/links_in_common(start,stop)} fscore = MinHeap() fscore.insert((start, distance_heuristic(start, stop))) #print(fscore) global article_data while len(unvisited) > 0: curr = fscore.extract()[0] print(ancestor_chain(parent, curr)) if curr == stop: unwrap_path(parent, start, stop) break try: unvisited.remove(curr) visited.append(curr) curr_links = get_page_links(curr)["parse"]["links"] for l in curr_links: try: if l["exists"] == "": link = l["*"] if (is_article(link)) and (link not in visited): tentative_gscore = gscore[curr] + 1 if link not in unvisited: unvisited.append(link) elif tentative_gscore >= gscore[link]: continue parent[link] = curr gscore[link] = tentative_gscore #fscore[link] = gscore[link] + (1/links_in_common(link,stop)) f = gscore[link] + distance_heuristic(link, stop) fscore.insert((link, f)) except: continue #print(fscore.array) #print("{0} of {1}".format(fscore.size,fscore.capacity)) except: continue del article_data[curr]
class TestMinHeapWithTuples(unittest.TestCase): def setUp(self): self.h = MinHeap( elements=[(4, 101), (12, 9), (13, 5), (2, 1), (6, 1001), (5, 45), (10, 121)]) def test_correct_order(self): self.assertEqual( self.h.h, [(2, 1), (4, 101), (5, 45), (12, 9), (6, 1001), (13, 5), (10, 121)], ) def test_insert_99_1(self): self.assertEqual(self.h.insert((1, 99)), 0) self.assertEqual( self.h.h, [ (1, 99), (2, 1), (5, 45), (4, 101), (6, 1001), (13, 5), (10, 121), (12, 9), ], ) def test_update_min(self): self.assertTrue((13, 5) in self.h) self.assertTrue((11, 5) not in self.h) self.h.update_min(11, 5) self.assertTrue((11, 5) in self.h) self.assertTrue((13, 5) not in self.h) self.assertEqual( self.h.h, [(2, 1), (4, 101), (5, 45), (12, 9), (6, 1001), (11, 5), (10, 121)], ) def test_pop(self): self.assertEqual(len(self.h.h), 7) self.assertEqual(self.h.pop(), (2, 1)) self.assertEqual(self.h.pop(), (4, 101)) self.assertEqual(self.h.pop(), (5, 45)) self.assertEqual(self.h.pop(), (6, 1001)) self.assertEqual(len(self.h.h), 3) self.assertEqual(self.h.h, [(10, 121), (12, 9), (13, 5)])
class TestMinHeapSort(unittest.TestCase): def setUp(self): self.h = MinHeap( values=[(4, 101), (12, 9), (13, 5), (2, 1), (6, 1001), (5, 45), (10, 121)]) def test_correct_order(self): self.assertEqual( self.h.h, [(2, 1), (4, 101), (5, 45), (12, 9), (6, 1001), (13, 5), (10, 121)], ) def test_insert_99_1(self): self.assertEqual(self.h.insert((1, 99)), 0) self.assertEqual( self.h.h, [ (1, 99), (2, 1), (5, 45), (4, 101), (6, 1001), (13, 5), (10, 121), (12, 9), ], ) def test_pop(self): self.assertEqual(len(self.h.h), 7) self.assertEqual(self.h.pop(), (2, 1)) self.assertEqual(self.h.pop(), (4, 101)) self.assertEqual(self.h.pop(), (5, 45)) self.assertEqual(self.h.pop(), (6, 1001)) self.assertEqual(len(self.h.h), 3) self.assertEqual(self.h.h, [(10, 121), (12, 9), (13, 5)])
class Median(object): def __init__(self, filename): self.H1 = MaxHeap([]) self.H2 = MinHeap([]) self.median = [] self.input_stream = [] self.load(filename) self.feed() def load(self, filename): file = open(filename, "r") data = file.readlines() for line in data: self.input_stream.append(int(line)) def print(self): print(self.median) def solve(self): total = 0 for i in range(len(self.median)): total += self.median[i] print(total % 10000) def feed(self): while (len(self.input_stream) > 0): num = self.input_stream.pop(0) h1_max = self.H1.findMax() if h1_max is None: h1_max = 0 h2_min = self.H2.findMin() if h2_min is None: h2_min = math.inf if num > h1_max and num < h2_min: if self.H1.length() >= self.H2.length(): self.H2.insert(num) else: self.H1.insert(num) else: if num < h1_max: self.H1.insert(num) elif num > h2_min: self.H2.insert(num) if self.H1.length() == self.H2.length(): self.median.append(self.H1.findMax()) elif self.H1.length() - self.H2.length() == 1: self.median.append(self.H1.findMax()) elif self.H2.length() - self.H1.length() == 1: self.median.append(self.H2.findMin()) elif self.H1.length() - self.H2.length() > 1: temp = self.H1.extractMax() self.H2.insert(temp) self.median.append(self.H1.findMax()) elif self.H2.length() - self.H1.length() > 1: temp = self.H2.extractMin() self.H1.insert(temp) self.median.append(self.H1.findMax()) else: print("????")
if costs[i] == 10000: print('inf', end=' ') else: print('{},{}'.format(costs[i], rmapping[parent[i]]), end=' ') print() # dijkstra part parent = [i for i in range(N)] visited = [False for _ in range(N)] costs = [10000 for _ in range(N)] heap = MinHeap() # for maintaining min cost element #initalization costs[src] = 0 heap.insert((0, src)) NN = '' while not heap.empty(): cw, cur = heap.poll() visited[cur] = True for v, w in graph[cur]: if not visited[v] and costs[v] > costs[cur] + w: costs[v] = costs[cur] + w heap.insert((costs[v], v)) parent[v] = cur NN += rmapping[cur] print(NN) print_so_far()
class TestMinHeap(unittest.TestCase): def setUp(self): self.heap = MinHeap() def test_clear(self): """Calling clear for a heap sets its array to an empty list and size to zero. (0p)""" self.heap.array = [(1, 1)] self.heap.size = 1 self.heap.clear() self.assertListEqual( [], self.heap.array, "heap.clear() should set heap.array to an empty list.") self.assertEqual(0, self.heap.size, "heap.clear() should set heap.size to 0.") def test_empty_heap_size(self): """The size of an empty heap is zero. (0p)""" self.assertEqual(0, self.heap.size, "The size of an empty heap should be zero.") def test_empty_heap_is__empty(self): """is_empty returns True for an empty heap. (0p)""" self.assertTrue( self.heap.is_empty(), "Calling is_empty should return True for an empty heap instance.") def test_higher_priority_high_low(self): """_higher_priority returns True when comparing an element with a higher priority to an element with a lower priority. (1p)""" self.heap.array = [(1, 'important'), (2, 'not important')] self.assertTrue( self.heap._higher_priority(0, 1), "_higher_priority priority should return True when comparing {0} to {1}" .format(self.heap.array[0], self.heap.array[1])) def test_higher_priority_low_high(self): """_higher_priority returns False when comparing an element with a lower priority to an element with a higher priority. (1p)""" self.heap.array = [(1, 'important'), (2, 'not important')] self.assertFalse( self.heap._higher_priority(1, 0), "_higher_priority priority should return False when comparing {0} to {1}" .format(self.heap.array[1], self.heap.array[0])) def test_size_after_insert(self): """Inserting values into the heap increments the size counter. (1p)""" inserted_tasks = generate_tasks_with_priorities() for pair in inserted_tasks: self.heap.insert(pair) inserted_count = len(inserted_tasks) current_size = self.heap.size self.assertEqual( inserted_count, current_size, "After inserting {0} pairs, the size of the heap should be {0}, not {1}" .format(inserted_count, current_size) + '\n' + heap_array_to_string(self.heap.array)) def test_empty_heap_top(self): """Calling top on an empty heap returns None. (1p)""" self.assertIsNone( self.heap.top(), "Calling heap.top() should return None for an empty heap instance." ) def test_empty_heap_pop(self): """Calling pop on an empty heap raises an exception. (1p)""" msg = "Calling heap.pop() should raise a RuntimeError for an empty heap instance." with self.assertRaises(RuntimeError, msg=msg): self.heap.pop() def test_top_after_insert(self): """Calling top always returns the object with the smallest priority value. (1p)""" inserted_tasks = generate_tasks_with_priorities() shuffled = list(inserted_tasks) random.shuffle(shuffled) for pair in shuffled: self.heap.insert(pair) expected_value = inserted_tasks[0][1] returned_value = self.heap.top() self.assertIs( returned_value, expected_value, "Calling top should have returned {0}, not {1}.".format( expected_value, returned_value) + '\n' + heap_array_to_string(self.heap.array)) def test_pop_after_insert(self): """Calling pop always returns the object with the smallest priority value and removes it from the heap. (1p)""" inserted_tasks = generate_tasks_with_priorities() shuffled = list(inserted_tasks) random.shuffle(shuffled) for pair in shuffled: self.heap.insert(pair) for i, pair in enumerate(inserted_tasks): assertmsg = "Before calling pop, the heap array in your solution looked like this:" heap_array_before_pop = self.heap.array[:] popped_value = self.heap.pop() expected_value = pair[1] self.assertIs( popped_value, expected_value, "Calling pop should have returned {0}, not {1}.".format( expected_value, popped_value) + '\n' + heap_array_to_string(heap_array_before_pop, assertmsg)) removed_count = i + 1 self.assertEqual( len(self.heap.array), len(inserted_tasks) - removed_count, "Calling pop should remove the object with the smallest priority value from the heap array." + '\n' + heap_array_to_string(heap_array_before_pop, assertmsg))
class TestMinHeap(unittest.TestCase): def setUp(self): self.h = MinHeap(elements=[2, 4, 5, 12, 13, 6, 10]) def test_parent_index(self): self.assertLess(self.h._parent_index(0), 0) self.assertEqual(self.h._parent_index(1), 0) self.assertEqual(self.h._parent_index(2), 0) self.assertEqual(self.h._parent_index(4), 1) self.assertEqual(self.h._parent_index(6), 2) def test_left_child_index(self): self.assertGreaterEqual(self.h._left_child_index(3), len(self.h)) self.assertGreaterEqual(self.h._left_child_index(5), len(self.h)) self.assertEqual(self.h._left_child_index(0), 1) self.assertEqual(self.h._left_child_index(1), 3) self.assertEqual(self.h._left_child_index(2), 5) def test_right_child_index(self): self.assertGreaterEqual(self.h._right_child_index(3), len(self.h)) self.assertGreaterEqual(self.h._right_child_index(6), len(self.h)) self.assertEqual(self.h._right_child_index(0), 2) self.assertEqual(self.h._right_child_index(1), 4) self.assertEqual(self.h._right_child_index(2), 6) def test_is_empty(self): self.assertFalse(self.h.is_empty()) self.assertTrue(MinHeap().is_empty()) def test_peek(self): self.assertEqual(self.h.peek(), self.h.h[0]) self.assertIsNone(MinHeap().peek()) def test_heapify_init(self): elements = [2, 4, 5, 6, 10, 12, 13] h = MinHeap(elements) self.assertEqual(h.h, [2, 4, 5, 6, 10, 12, 13]) def test_heapify_after_init(self): elements = [2, 4, 5, 6, 10, 12, 13] h = MinHeap() self.assertEqual(h.h, []) h._heapify(elements) self.assertEqual(h.h, [2, 4, 5, 6, 10, 12, 13]) def test_insert_1(self): self.assertEqual(self.h.insert(1), 0) self.assertEqual(self.h.h, [1, 2, 5, 4, 13, 6, 10, 12]) def test_insert_3(self): self.assertEqual(self.h.insert(3), 1) self.assertEqual(self.h.h, [2, 3, 5, 4, 13, 6, 10, 12]) def test_insert_10(self): self.assertEqual(self.h.insert(9), 3) self.assertEqual(self.h.h, [2, 4, 5, 9, 13, 6, 10, 12]) def test_insert_15(self): self.assertEqual(self.h.insert(15), 7) self.assertEqual(self.h.h, [2, 4, 5, 12, 13, 6, 10, 15]) def test_update_min(self): self.assertTrue(9 not in self.h) self.assertTrue(10 in self.h) self.h.update_min(9, 10) self.assertTrue(9 in self.h) self.assertTrue(10 not in self.h) self.assertEqual(self.h.h, [2, 4, 5, 12, 13, 6, 9]) def test_pop_empty(self): h = MinHeap() self.assertIsNone(h.pop()) self.assertEqual(h.h, [])