예제 #1
0
 def setUp(self):
     vals = list(range(1, 1000))
     random.shuffle(vals)
     self.H = MinHeap()
     '''insert random values into structure'''
     for i in vals:
         self.H.insertNode(i, i)
예제 #2
0
파일: huffman.py 프로젝트: jessicaprt/c275
def make_tree (freq_table):

    trees = MinHeap()
    trees.add(1, TreeLeafEndMessage())
    for (symbol, freq) in freq_table.items():
        trees.add(freq, TreeLeaf(symbol))

    while len(trees) > 1:
        (rfreq, right) = trees.pop_min()
        (lfreq, left) = trees.pop_min()
        trees.add(lfreq+rfreq, TreeBranch(left, right))

    (totalfreq, tree) = trees.pop_min()
    return tree
예제 #3
0
파일: 1-http.py 프로젝트: jgauth/cis313
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)
예제 #4
0
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
예제 #5
0
class MinHeapTest(unittest.TestCase):
    def setUp(self):
        vals = list(range(1, 1000))
        random.shuffle(vals)
        self.H = MinHeap()
        '''insert random values into structure'''
        for i in vals:
            self.H.insertNode(i, i)

    def test_extractMin(self):
        '''test extract min'''
        expectedmin = 1
        for _ in range(self.H.count):
            #empty the heap to completion
            v, k = self.H.extractMin()
            self.assertEqual(v, expectedmin)
            expectedmin += 1
예제 #6
0
 def encode(self):
     occurrences = self._count_occurrences()
     heap = MinHeap.build_from_dict(occurrences)
     root = heap.merge_to_single_element()
     self.mappings = self._generate_mappings(root)
     self.encoded_digit_sequence = self._replace_with_mappings()
     self.encoded_content = self._encode()
     return self.encoded_content, self.reversed_mappings
def least_cost_path (graph, coord, start, dest, cost):
	'''This function takes in any graph supplied by the user, by default the only graph built by the 
	script is the edmonton roads graph. This function can also take in any cost function of two 
	variables, start and destination. 
	'''
	heap = MinHeap()				# create a min heap
	heap.add(0, (start, start)) 			# dist, (vertice, prior vertice)
	reached = {}					# dictionary of vertices reached with their shortest cost and prior vertice
	while not heap.isempty():			# run the program until the heap is empty
		curr_dist, (curr_vert, pri_vert) = heap.pop_min()	# pop the min cost vertice and explore it, aka extract minimum distance runner
		for v in graph.neighbours(curr_vert):
			temp_dist = curr_dist + cost(coord, curr_vert, v) 					# Find new distance            
			if (v in reached and temp_dist < reached[v][1]) or v not in reached:		# Check if the key has been used already
				reached[v] = (curr_vert, temp_dist)	# Previous Vertice, distance
				if v != dest:
					heap.add(temp_dist, (v, curr_vert))	
	
	min_path = []				# Trace back the shortest path
	
	if dest in reached:			# First check if there is even a path
		min_path.insert(0,dest)		
		curr_id = reached[dest][0]
		prior_id = dest
		while prior_id != start:		# trace back until we reach the start from dest
			min_path.insert(0,curr_id)	# keep adding prior vert to front of list
			prior_id = curr_id
			if prior_id not in reached:	
				return min_path
			curr_id = reached[prior_id][0]
			
	return min_path, reached[dest]
예제 #8
0
파일: dijkstra.py 프로젝트: ldunphy1/504
def dijkstra(aGraph, start, queue="FibHeap"):

    # Set the distance for the start node to zero
    start.set_distance(0)

    # Put the tuple pair into the priority queue
    unvisited_queue = [(v.get_distance, v) for v in aGraph]
    pyheap = False  #building and rebuilding this queue is different can eventually just change background code
    minheap = False

    if queue == "FibHeap":
        print("Using Fiobonnaci Heap Structure...\n")
        # Initialize new FibHeap
        obj = FibHeap()
    elif queue == "MinHeap":
        #print("Using Heapq Data Structure From Python...\n")
        minheap = True
        obj = MinHeap()
    elif queue == "Binomial":
        #print("Using Binomial Heap Structure...\n")
        obj = BinomialHeap()

    #Build the heap

    for index, item in enumerate(unvisited_queue):
        obj.insertNode(item[1].get_distance(), item)
        for next in item[1].adjacent:
            obj.insertNode(item[1].get_weight(next) + item[1].get_distance(),
                           next)  #store in tree based on weights

    while (len(unvisited_queue)):
        min, key = obj.extractMin()
        current = key[1]
        current.set_visited()  #set vertex to visited

        # now visit adj nodes
        for next in current.adjacent:
            #if already visited just skip
            if next.visited:
                continue
            new_dist = current.get_distance() + current.get_weight(next)

            #check if new_dist is smaller
            if new_dist < next.get_distance():
                next.set_distance(new_dist)
                next.set_previous(current)
                #print( 'updated : current = %s next = %s new_dist = %s' % (current.get_id(), next.get_id(), next.get_distance()))
        # Empty and Rebuild heap
        obj.emptyHeap()
        unvisited_queue = [(v.get_distance, v) for v in aGraph
                           if not v.visited]
        for index, item in enumerate(unvisited_queue):
            obj.insertNode(item[1].get_distance(), item)
            for next in item[1].adjacent:
                obj.insertNode(item[1].get_weight(next) +
                               item[1].get_distance(),
                               next)  #store in tree based on weights
예제 #9
0
def least_cost_path(graph, start, dest, cost):
	reached = {}
	# For faster implementation, use MinHeap to substitute runners
	tree = MinHeap()
	tree.add((0, start, start), None)
	while tree and dest not in reached:
		#print("tree: " + str(tree._array))
		(dist, prev, curr) = tree.pop_min()[0]
		if curr in reached:
			continue
		reached[curr] = prev
		for succ in graph.neighbours(curr):
			tree.add((dist + cost(curr, succ), curr, succ), None)
	if dest not in reached:
		return []
	#print("reached: ", reached)
	path = []
	v = dest
	while True:
		path.append(v)
		if path[-1] == start:
			break
		v = reached[v]
	path = path[::-1]
	#print("path: ", path)
	return path
예제 #10
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)
예제 #11
0
파일: main.py 프로젝트: memeda/algorithm
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())
예제 #12
0
파일: test.py 프로젝트: pragaashp/lib-tools
	def setUpClass(self):
		self.H = MinHeap()
		self.data = [('A',7),('B',3),('C',4),('D',1),('E',6),('F',5),('G',2)]
예제 #13
0
파일: test.py 프로젝트: pragaashp/lib-tools
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)
예제 #14
0
 def test_peek(self):
     item = {"id":1, "price":1.0}
     heap = MinHeap()
     heap.push(item)
     self.assertEqual(heap.peek(), item)