示例#1
0
    def pq_sort(self, test_array):
        pq = PriorityQueue()

        for x in test_array:
            pq.insert(x)

        pq_size = pq.size()
        return [pq.extract_min() for x in range(pq_size)]
示例#2
0
    def test_size_remove(self):
        pq = PriorityQueue()

        for i in range(100):
            pq.insert(i)

        for i in range(100):
            pq.extract_min()

        self.assertEqual(pq.size(), 0)
示例#3
0
def Dijkstra(g,gn,s,d):
    #initialization
    dist = {}
    prev = {}

    Q = PriorityQueue()
#    print(g["home"].keys())
    #출발노드 s는 자신까지의 거리가 0이고 자신의 predecessor
    dist[s] = 0
    prev[s] = None

    #다른 노드들은 모두 거리를 infinity로 설정하고 predecessor는 일단 None으로 설정하고
    '''for n in g:
        dist[n[0]] = float('inf')
        prev[n[0]] = None
        dist[n[1]] = float('inf')
        prev[n[1]] = None
    '''
    #그러면서 PQ에다가 노드들을 넣어줍니다.
    for n in g.keys():
        if n != s :
            dist[n] = float('inf')
            prev[n] = None
        
        if n in g[s].keys():
            dist[n] = float('inf')
            prev[n] = None
        Q.insert(dist[n],n) # n이 우선순위 dist가 value
    #PQ가 빌때까지 계속 루프를 돌면서,
    while Q.size() > 0:
        p,u = Q.pop() #현재까지 가장 짧은 거리를 갖고 있는 노드를 pop

        #꺼낸 노드의 각 이웃들까지의 거리를 현재 자신까지의 minimum cost와 더한 후
        #이웃들이 가지고 있는 거리보다 작으면 이것으로 업데이트 시키고 다시 PQ에 넣거나 update합니다
        #pd insert 기능에 포함되어 있다고 한다.
        '''for v in g[u].keys():
#           alt = dist[u] + g[u][v].get('weight',1)
            alt = dist[u] + g[u][v]
            if alt < dist[v]:
                dist[v] = alt
                prev[v] = u
                Q.insert(dist[v],v)       #for v in g.neighbors(u):
        '''
        for v in g[u].keys():
#       alt = dist[u] + g[u][v].get('weight',1)
            alt = dist[u] + int(g[u][v][0])  # distance 계산에 쓰임.
            alt2 = dist[u] + int(gn[u][v][0])  # 경로 선택에 쓰임.
            if alt2 < dist[v]:
                dist[v] = alt
                prev[v] = u
                Q.insert(dist[v],v)
    return dist, prev
示例#4
0
def get_huffman_tree(frequency_lst):
    frequency_lst = Counter(s)
    pq = PriorityQueue()
    for char, freq in frequency_lst:
        pq.insert(freq, TreeNode(char))

    while pq.size() > 1:
        freq1, node1 = pq.delete_min()
        freq2, node2 = pq.delete_min()

        internal_node = TreeNode(node1.val + node2.val, node1, node2)
        pq.insert(freq1 + freq2, internal_node)

    _, root = pq.delete_min()
    return get_code(root)
示例#5
0
class MaxHeap(object):
    def __init__(self, lst=[]):
        lst = [(-prio, ele) for (prio, ele) in lst]
        self.maxHeap = PriorityQueue(lst)

    def insert(self, priority, ele):
        self.maxHeap.insert(-priority, ele)

    def delete_max(self):
        prio, ele = self.maxHeap.delete_min()
        return -prio, ele

    def get_max(self):
        prio, ele = self.maxHeap.get_min()
        return -prio, ele

    def size(self):
        return self.maxHeap.size()
class InformedSearch(Search):
    """
    Implement this.
    """
    def __init__(self, initial_state, goal_state, verbose=False):
        self.node_expansions = 0
        self.unique_states = {}
        self.unique_states[initial_state.dictkey()] = True
        self.q = PriorityQueue()
        self.goal_state = goal_state
        self.q.enqueue(InformedNode(initial_state, None, 0, self.goal_state))
        self.verbose = verbose
        solution = self.execute()
        if solution is None:
            print("Search failed")
        else:
            self.showPath(solution)

    def execute(self):
        while not self.q.empty():
            current = self.q.dequeue()
            self.node_expansions += 1
            if self.goal_state.equals(current.state):
                return current
            else:
                successors = current.state.applyOperators()
                for next_state in successors:
                    if next_state.dictkey() not in self.unique_states.keys():
                        n = InformedNode(next_state, current,
                                         current.depth + 1, self.goal_state)
                        self.q.enqueue(n)
                        self.unique_states[next_state.dictkey()] = True
                    if self.verbose:
                        print("Expanded:", current)
                        print("Number of successors:", len(successors))
                        print("Queue length: ", self.q.size())
                        print("-------------------------------")
        return None

    def get_expansions(self):
        return self.node_expansions
示例#7
0
 def test_size_insert(self):
     pq = PriorityQueue()
     for i in range(100):
         self.assertEqual(pq.size(), i)
         pq.insert(i)
示例#8
0
 def test_size_initial(self):
     pq = PriorityQueue()
     self.assertEqual(pq.size(), 0)
示例#9
0
 def test_size_insert(self):
     pq = PriorityQueue()
     for i in range(100):
         self.assertEqual(pq.size(), i)
         pq.insert(i)
示例#10
0
 def test_size_initial(self):
     pq = PriorityQueue()
     self.assertEqual(pq.size(), 0)