示例#1
0
    def shortest_path(self, v_start, v_end):
        # item structure: {'w': 11, 'path': ['va', 'vb', ...]}
        priority_queue = MinHeap(criterion='w')
        # structure: {..., 'v_name': {'w': 11, 'path': ['va', 'vb',...] }}
        best_tracks = {}

        curr_track = {'path': [v_start], 'w': 0, 'v': v_start}
        while True:
            for edge in self.vertex_edges[curr_track['v']]:
                new_track = {
                    'w': curr_track['w'] + edge['w'],
                    'path': curr_track['path'] + [edge['v2']]
                }
                priority_queue.insert(new_track)

            assert priority_queue.is_empty() == False
            min_track = priority_queue.getMin()

            while better_track_exists(min_track, best_tracks):
                min_track = priority_queue.getMin()

            if at_destination(min_track, v_end):
                return min_track

            best_tracks[min_track['path'][-1]] = min_track
            curr_track = min_track.copy()
            curr_track['v'] = min_track['path'][-1]
示例#2
0
    def shortest_path(self, start: Vertice, destination: Vertice,
                      time: float) -> tuple:
        for v in self.__v.values():
            v.set_distance(-1)
            v.set_parrent(None)

        unexplored = MinHeap(len(self.__v))
        for v in self.__v.values():
            unexplored.insert(v)
        unexplored.update(start.v_id(), 0)
        self.__v[start.v_id()].set_distance(0)

        traffic = 0
        for edge in self.__traffic.keys():
            for t in self.__traffic[edge]:
                if time <= t:
                    traffic += 1

            v = self.__v[edge[0]]
            u = self.__v[edge[1]]
            self.set_e_weight(v, u, self.__weight(v, u, traffic))
            traffic = 0

        explored = []
        while not destination.v_id() in explored:
            v = unexplored.pop_min()
            explored.append(v.v_id())
            for edge in self.__adj[v.v_id()]:
                if v.distance() + edge[1] < self.__v[edge[0]].distance():
                    unexplored.update(edge[0], v.distance() + edge[1])
                    self.__v[edge[0]].set_distance(v.distance() + edge[1])
                    self.__v[edge[0]].set_parrent(v)

        finded_path = []
        curr = destination
        travel_time = 0

        while curr is not start:
            finded_path.append(curr.v_id())
            travel_time += self.e_weight(curr, curr.parrent())
            curr = curr.parrent()

        travel_time *= 120

        finded_path.append(curr.v_id())
        for i in range(len(finded_path) - 1):
            self.__traffic[(finded_path[i],
                            finded_path[i + 1])].append(time + travel_time)
            self.__traffic[(finded_path[i + 1],
                            finded_path[i])].append(time + travel_time)
        finded_path.append(travel_time)

        return tuple(reversed(finded_path))
示例#3
0
    def solve_with_a_star(self):
        path = []
        openList = MinHeap([])
        entryFinder = {}
        initial_cost = self.heuristic[self.startingNode]
        openList.insert(initial_cost, [self.startingNode, []])
        entryFinder[self.startingNode] = 0
        closedList = []
        memory_spend = 0

        for i in range(1, MAX_ATTEMPTS):
            if openList.heap_size is 0:
                raise Exception("Not found a solution")
            else:
                if openList.heap_size > memory_spend:
                    memory_spend = openList.heap_size
                p = openList.extract_min()
                cost_until_now = p[0]
                actual_city = p[1][0]
                if actual_city in entryFinder:
                    entryFinder.pop(actual_city)
                if actual_city in self.objectives:
                    finalPath = p[1][1]
                    finalPath.append(actual_city)
                    print(memory_spend)
                    print(finalPath)
                    print(cost_until_now)
                    return
                adj_cities = self.graph[actual_city]
                closedList.append(actual_city)
                for adj_city in adj_cities:
                    if adj_city not in closedList:
                        gx = (cost_until_now - self.heuristic[actual_city]
                              ) + adj_cities[adj_city]['distance']
                        cost = gx + self.heuristic[adj_city]
                        if adj_city not in entryFinder:
                            path = p[1][1]
                            newPath = list(path)
                            newPath.append(actual_city)
                            openList.insert(cost, [adj_city, newPath])
                            entryFinder[adj_city] = cost
                        else:
                            if cost < entryFinder[adj_city]:
                                path = p[1][1]
                                newPath = list(path)
                                newPath.append(actual_city)
                                for i in range(1, openList.heap_size):
                                    if openList.heap[i][1][0] == adj_city:
                                        openList.heap[i][1][1] = newPath
                                        openList.decrease_priority(i, cost)
                                        entryFinder[adj_city] = cost
                                        break
        raise Exception("Max attempts reached")
def dijkstra(source, graph):
    cnt = 1
    distance = {}
    heap = MinHeap(len(graph.nodes))
    for i in graph.nodes:
        distance[i] = float('inf')
    distance[source] = 0

    heap.insert((0, source))

    while cnt != 0:
        dist, node = heap.removeMin()
        cnt -= 1
        for i in graph.adjList[node]:
            if distance[i[0]] > dist + i[1]:
                distance[i[0]] = dist + i[1]
                heap.insert((distance[i[0]], i[0]))
                cnt += 1
    return distance
示例#5
0
文件: mediana.py 项目: kitz99/misc
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
        else:
            print sup.max()
示例#6
0
def a_star(start_state,
           heuristic_func,
           successors_gen,
           goal_predicate,
           cost_func=lambda *_: 1):
    """
    Generalized implementation of A* search.

    Input:
        start_state:        Initial state
        heuristic_func:     Function of the form (state) -> heuristic value
        successors_gen:     Generator which yields all successors for a given state: 
                                state -> yield successor state
        goal_predicate:     Predicate to test whether the given state is a goal state:
                                state -> True or False

        (Optional)
        cost_func:          Function which returns the cost of a state transition:
                                from_state, to_state -> cost
                            Defaults to a cost of one.
    
    Returns:
        A list of the form 
            [(x0, y0), (x1, y1), ..., (xn, yn)] 
        representing a path from start to end node.
    """
    # Memoization table, maps from state to corresponding node
    memo = {}

    # Initialize containers
    closed = set()
    open_ = MinHeap(key_attr='f')

    # Initialize starting node
    start = initialize_start_node(start_state, heuristic_func)
    open_.insert(start)
    memo[start_state] = start

    # Loop as long as there are nodes to process
    while open_:
        u = open_.extract_min()
        closed.add(u)

        # Test to see if goal state is reached
        if goal_predicate(u.state):
            print("Goal found!")
            return [node.state[1:] for node in create_path_to(u)]

        # Process successor states of current node
        for v_state in successors_gen(u.state):
            # Check if state has been previously encountered, create new by default
            if v_state in memo:
                v = memo[v_state]
            else:
                v = initialize_successor_node(u, v_state, heuristic_func,
                                              cost_func)
                memo[v_state] = v

            # Add to parents' list of successors
            u.successors.append(v)

            # In case of encountering a new node (not opened or closed)
            if v not in open_ and v not in closed:
                attach_and_eval(v, u, heuristic_func, cost_func)
                open_.insert(v)
            # If path is an improvement to previously discovered node
            elif u.g + cost_func(u.state, v.state) < v.g:
                attach_and_eval(v, u, heuristic_func, cost_func)
                # If successor is an internal node
                if v in closed:
                    propagate_path_improvements(v, heuristic_func, cost_func)
示例#7
0
from min_heap import MinHeap

heap = MinHeap()
heap.insert(5)
heap.insert(10)
heap.insert(1)
heap.insert(4)
heap.insert(7)
heap.insert(2)
print(heap)
print(heap.min())
print(heap.remove())
print(heap)
print(heap.remove())
print(heap)