function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def __lt__(self, other) -> bool: return self.f_cost < other.f_cost
graphs
def __init__(self, start: tuple[int, int], goal: tuple[int, int]): self.start = Node(start[1], start[0], goal[1], goal[0], 0, None) self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None) self.open_nodes = [self.start] self.closed_nodes: list[Node] = [] self.reached = False
graphs
def search(self) -> Path | None: while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() current_node = self.open_nodes.pop(0) if current_node.pos == self.target.pos: self.reached = True return self.retrace_path(current_node) self.closed_nodes.append(current_node) successors = self.get_successors(current_node) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(child_node) else: # retrieve the best current path better_node = self.open_nodes.pop(self.open_nodes.index(child_node)) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(child_node) else: self.open_nodes.append(better_node) if not self.reached: return [self.start.pos] return None
graphs
def get_successors(self, parent: Node) -> list[Node]: successors = [] for action in delta: pos_x = parent.pos_x + action[1] pos_y = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent.g_cost + 1, parent, ) ) return successors
graphs
def retrace_path(self, node: Node | None) -> Path: current_node = node path = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) current_node = current_node.parent path.reverse() return path
graphs
def get_distinct_edge(edge_array): distinct_edge = set() for row in edge_array: for item in row: distinct_edge.add(item[0]) return list(distinct_edge)
graphs
def get_bitcode(edge_array, distinct_edge): bitcode = ["0"] * len(edge_array) for i, row in enumerate(edge_array): for item in row: if distinct_edge in item[0]: bitcode[i] = "1" break return "".join(bitcode)
graphs
def get_frequency_table(edge_array): distinct_edge = get_distinct_edge(edge_array) frequency_table = {} for item in distinct_edge: bit = get_bitcode(edge_array, item) # print('bit',bit) # bt=''.join(bit) s = bit.count("1") frequency_table[item] = [s, bit] # Store [Distinct edge, WT(Bitcode), Bitcode] in descending order sorted_frequency_table = [ [k, v[0], v[1]] for k, v in sorted(frequency_table.items(), key=lambda v: v[1][0], reverse=True) ] return sorted_frequency_table
graphs
def get_nodes(frequency_table): nodes = {} for _, item in enumerate(frequency_table): nodes.setdefault(item[2], []).append(item[0]) return nodes
graphs
def get_cluster(nodes): cluster = {} for key, value in nodes.items(): cluster.setdefault(key.count("1"), {})[key] = value return cluster
graphs
def get_support(cluster): return [i * 100 / len(cluster) for i in cluster]
graphs
def print_all() -> None: print("\nNodes\n") for key, value in nodes.items(): print(key, value) print("\nSupport\n") print(support) print("\n Cluster \n") for key, value in sorted(cluster.items(), reverse=True): print(key, value) print("\n Graph\n") for key, value in graph.items(): print(key, value) print("\n Edge List of Frequent subgraphs \n") for edge_list in freq_subgraph_edge_list: print(edge_list)
graphs
def create_edge(nodes, graph, cluster, c1): for i in cluster[c1]: count = 0 c2 = c1 + 1 while c2 < max(cluster.keys()): for j in cluster[c2]: if int(i, 2) & int(j, 2) == int(i, 2): if tuple(nodes[i]) in graph: graph[tuple(nodes[i])].append(nodes[j]) else: graph[tuple(nodes[i])] = [nodes[j]] count += 1 if count == 0: c2 = c2 + 1 else: break
graphs
def construct_graph(cluster, nodes): x = cluster[max(cluster.keys())] cluster[max(cluster.keys()) + 1] = "Header" graph = {} for i in x: if (["Header"],) in graph: graph[(["Header"],)].append(x[i]) else: graph[(["Header"],)] = [x[i]] for i in x: graph[(x[i],)] = [["Header"]] i = 1 while i < max(cluster) - 1: create_edge(nodes, graph, cluster, i) i = i + 1 return graph
graphs
def my_dfs(graph, start, end, path=None): path = (path or []) + [start] if start == end: paths.append(path) for node in graph[start]: if tuple(node) not in path: my_dfs(graph, tuple(node), end, path)
graphs
def find_freq_subgraph_given_support(s, cluster, graph): k = int(s / 100 * (len(cluster) - 1)) for i in cluster[k]: my_dfs(graph, tuple(cluster[k][i]), (["Header"],))
graphs
def freq_subgraphs_edge_list(paths): freq_sub_el = [] for edges in paths: el = [] for j in range(len(edges) - 1): temp = list(edges[j]) for e in temp: edge = (e[0], e[1]) el.append(edge) freq_sub_el.append(el) return freq_sub_el
graphs
def preprocess(edge_array): for i in range(len(edge_array)): for j in range(len(edge_array[i])): t = edge_array[i][j].split("-") edge_array[i][j] = t
graphs
def search( grid: list[list[int]], init: list[int], goal: list[int], cost: int, heuristic: list[list[int]], ) -> tuple[list[list[int]], list[list[int]]]: closed = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the reference grid closed[init[0]][init[1]] = 1 action = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the action grid x = init[0] y = init[1] g = 0 f = g + heuristic[x][y] # cost from starting cell to destination cell cell = [[f, g, x, y]] found = False # flag that is set when search is complete resign = False # flag set if we can't find expand while not found and not resign: if len(cell) == 0: raise ValueError("Algorithm is unable to find solution") else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() next_cell = cell.pop() x = next_cell[2] y = next_cell[3] g = next_cell[1] if x == goal[0] and y == goal[1]: found = True else: for i in range(len(DIRECTIONS)): # to try out different valid actions x2 = x + DIRECTIONS[i][0] y2 = y + DIRECTIONS[i][1] if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]): if closed[x2][y2] == 0 and grid[x2][y2] == 0: g2 = g + cost f2 = g2 + heuristic[x2][y2] cell.append([f2, g2, x2, y2]) closed[x2][y2] = 1 action[x2][y2] = i invpath = [] x = goal[0] y = goal[1] invpath.append([x, y]) # we get the reverse path from here while x != init[0] or y != init[1]: x2 = x - DIRECTIONS[action[x][y]][0] y2 = y - DIRECTIONS[action[x][y]][1] x = x2 y = y2 invpath.append([x, y]) path = [] for i in range(len(invpath)): path.append(invpath[len(invpath) - 1 - i]) return path, action
graphs
def print_distance(distance: list[float], src): print(f"Vertex\tShortest Distance from vertex {src}") for i, d in enumerate(distance): print(f"{i}\t\t{d}")
graphs
def check_negative_cycle( graph: list[dict[str, int]], distance: list[float], edge_count: int ): for j in range(edge_count): u, v, w = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: return True return False
graphs
def bellman_ford( graph: list[dict[str, int]], vertex_count: int, edge_count: int, src: int ) -> list[float]: distance = [float("inf")] * vertex_count distance[src] = 0.0 for _ in range(vertex_count - 1): for j in range(edge_count): u, v, w = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: distance[v] = distance[u] + w negative_cycle_exists = check_negative_cycle(graph, distance, edge_count) if negative_cycle_exists: raise Exception("Negative cycle found") return distance
graphs
def _input(message): return input(message).strip().split(" ")
graphs
def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) return graph
graphs
def initialize_unweighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) graph[y].append(x) return graph
graphs
def initialize_weighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[tuple[int, int]]]: graph: dict[int, list[tuple[int, int]]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")) graph[x].append((y, w)) graph[y].append((x, w)) return graph
graphs
def dfs(g, s): vis, _s = {s}, [s] print(s) while _s: flag = 0 for i in g[_s[-1]]: if i not in vis: _s.append(i) vis.add(i) flag = 1 print(i) break if not flag: _s.pop()
graphs
def bfs(g, s): vis, q = {s}, deque([s]) print(s) while q: u = q.popleft() for v in g[u]: if v not in vis: vis.add(v) q.append(v) print(v)
graphs
def dijk(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1] path[v[0]] = u for i in dist: if i != s: print(dist[i])
graphs
def topo(g, ind=None, q=None): if q is None: q = [1] if ind is None: ind = [0] * (len(g) + 1) # SInce oth Index is ignored for u in g: for v in g[u]: ind[v] += 1 q = deque() for i in g: if ind[i] == 0: q.append(i) if len(q) == 0: return v = q.popleft() print(v) for w in g[v]: ind[w] -= 1 if ind[w] == 0: q.append(w) topo(g, ind, q)
graphs
def adjm(): n = input().strip() a = [] for _ in range(n): a.append(map(int, input().strip().split())) return a, n
graphs
def floy(a_and_n): (a, n) = a_and_n dist = list(a) path = [[0] * n for i in range(n)] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k print(dist)
graphs
def prim(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known and v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1] path[v[0]] = u return dist
graphs
def edglist(): n, m = map(int, input().split(" ")) edges = [] for _ in range(m): edges.append(map(int, input().split(" "))) return edges, n
graphs
def krusk(e_and_n): # Sort edges on the basis of distance (e, n) = e_and_n e.sort(reverse=True, key=lambda x: x[2]) s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break print(s) x = e.pop() for i in range(len(s)): if x[0] in s[i]: break for j in range(len(s)): if x[1] in s[j]: if i == j: break s[j].update(s[i]) s.pop(i) break
graphs
def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index
graphs
def create_graph(n, edges): g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) return g
graphs
def bfs(): while not queue.empty(): u = queue.get() visited[u] = True for neighbour in graph[u]: if neighbour == u: return False if color[neighbour] == -1: color[neighbour] = 1 - color[u] queue.put(neighbour) elif color[neighbour] == color[u]: return False return True
graphs
def __init__(self, num_of_nodes: int) -> None: self.m_num_of_nodes = num_of_nodes self.m_edges: list[list[int]] = [] self.m_component: dict[int, int] = {}
graphs
def add_edge(self, u_node: int, v_node: int, weight: int) -> None: if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node])
graphs
def set_component(self, u_node: int) -> None: in terms of size, and attaches the smaller one to the larger one to form # Initialize additional lists required to algorithm. component_size = [] mst_weight = 0 minimum_weight_edge: list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes): self.m_component.update({node: node}) component_size.append(1) num_of_components = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: u, v, w = edge u_component = self.m_component[u] v_component = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): minimum_weight_edge[component] = [u, v, w] for edge in minimum_weight_edge: if isinstance(edge, list): u, v, w = edge u_component = self.m_component[u] v_component = self.m_component[v] if u_component != v_component: mst_weight += w self.union(component_size, u_component, v_component) print(f"Added edge [{u} - {v}]\nAdded weight: {w}\n") num_of_components -= 1 minimum_weight_edge = [-1] * self.m_num_of_nodes print(f"The total weight of the minimal spanning tree is: {mst_weight}")
graphs
def test_vector() -> None:
graphs
def __init__(self, n): self.lvl = [0] * n self.ptr = [0] * n self.q = [0] * n self.adj = [[] for _ in range(n)]
graphs
def add_edge(self, a, b, c, rcap=0): self.adj[a].append([b, len(self.adj[b]), c, 0]) self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0])
graphs
def depth_first_search(self, vertex, sink, flow): if vertex == sink or not flow: return flow for i in range(self.ptr[vertex], len(self.adj[vertex])): e = self.adj[vertex][i] if self.lvl[e[0]] == self.lvl[vertex] + 1: p = self.depth_first_search(e[0], sink, min(flow, e[2] - e[3])) if p: self.adj[vertex][i][3] += p self.adj[e[0]][e[1]][3] -= p return p self.ptr[vertex] = self.ptr[vertex] + 1 return 0
graphs
def max_flow(self, source, sink): flow, self.q[0] = 0, source for l in range(31): # noqa: E741 l = 30 maybe faster for random data while True: self.lvl, self.ptr = [0] * len(self.q), [0] * len(self.q) qi, qe, self.lvl[source] = 0, 1, 1 while qi < qe and not self.lvl[sink]: v = self.q[qi] qi += 1 for e in self.adj[v]: if not self.lvl[e[0]] and (e[2] - e[3]) >> (30 - l): self.q[qe] = e[0] qe += 1 self.lvl[e[0]] = self.lvl[v] + 1 p = self.depth_first_search(source, sink, INF) while p: flow += p p = self.depth_first_search(source, sink, INF) if not self.lvl[sink]: break return flow
graphs
def dfs(u, graph, visited_edge, path=None): path = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: visited_edge[u][v], visited_edge[v][u] = True, True path = dfs(v, graph, visited_edge, path) return path
graphs
def check_circuit_or_path(graph, max_node): odd_degree_nodes = 0 odd_node = -1 for i in range(max_node): if i not in graph.keys(): continue if len(graph[i]) % 2 == 1: odd_degree_nodes += 1 odd_node = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node
graphs
def check_euler(graph, max_node): visited_edge = [[False for _ in range(max_node + 1)] for _ in range(max_node + 1)] check, odd_node = check_circuit_or_path(graph, max_node) if check == 3: print("graph is not Eulerian") print("no path") return start_node = 1 if check == 2: start_node = odd_node print("graph has a Euler path") if check == 1: print("graph has a Euler cycle") path = dfs(start_node, graph, visited_edge) print(path)
graphs
def main(): g1 = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} g2 = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} g3 = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} g4 = {1: [2, 3], 2: [1, 3], 3: [1, 2]} g5 = { 1: [], 2: [] # all degree is zero } max_node = 10 check_euler(g1, max_node) check_euler(g2, max_node) check_euler(g3, max_node) check_euler(g4, max_node) check_euler(g5, max_node)
graphs
def print_dist(dist, v): print("\nVertex Distance") for i in range(v): if dist[i] != float("inf"): print(i, "\t", int(dist[i]), end="\t") else: print(i, "\t", "INF", end="\t") print()
graphs
def min_dist(mdist, vset, v): min_val = float("inf") min_ind = -1 for i in range(v): if (not vset[i]) and mdist[i] < min_val: min_ind = i min_val = mdist[i] return min_ind
graphs
def dijkstra(graph, v, src): mdist = [float("inf") for _ in range(v)] vset = [False for _ in range(v)] mdist[src] = 0.0 for _ in range(v - 1): u = min_dist(mdist, vset, v) vset[u] = True for i in range(v): if ( (not vset[i]) and graph[u][i] != float("inf") and mdist[u] + graph[u][i] < mdist[i] ): mdist[i] = mdist[u] + graph[u][i] print_dist(mdist, i)
graphs
def random_graph( vertices_number: int, probability: float, directed: bool = False ) -> dict: graph: dict = {i: [] for i in range(vertices_number)} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(vertices_number) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(vertices_number): for j in range(i + 1, vertices_number): if random.random() < probability: graph[i].append(j) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(i) return graph
graphs
def complete_graph(vertices_number: int) -> dict: return { i: [j for j in range(vertices_number) if i != j] for i in range(vertices_number) }
graphs
def print_stack(stack, clothes): order = 1 while stack: current_clothing = stack.pop() print(order, clothes[current_clothing]) order += 1
graphs
def depth_first_search(u, visited, graph): visited[u] = 1 for v in graph[u]: if not visited[v]: depth_first_search(v, visited, graph) stack.append(u)
graphs
def topological_sort(graph, visited): for v in range(len(graph)): if not visited[v]: depth_first_search(v, visited, graph)
graphs
def dfs(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True for v in graph[u]: dfs(v) stack.append(u)
graphs
def dfs2(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True component.append(u) for v in reversed_graph[u]: dfs2(v)
graphs
def kosaraju(): global graph, reversed_graph, scc, component, visit, stack for i in range(n): dfs(i) visit = [False] * n for i in stack[::-1]: if visit[i]: continue component = [] dfs2(i) scc.append(component) return scc
graphs
def __init__( self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Node | None ): self.pos_x = pos_x self.pos_y = pos_y self.pos = (pos_y, pos_x) self.goal_x = goal_x self.goal_y = goal_y self.parent = parent
graphs
def __init__(self, start: tuple[int, int], goal: tuple[int, int]): self.start = Node(start[1], start[0], goal[1], goal[0], None) self.target = Node(goal[1], goal[0], goal[1], goal[0], None) self.node_queue = [self.start] self.reached = False
graphs
def search(self) -> Path | None: while self.node_queue: current_node = self.node_queue.pop(0) if current_node.pos == self.target.pos: self.reached = True return self.retrace_path(current_node) successors = self.get_successors(current_node) for node in successors: self.node_queue.append(node) if not self.reached: return [self.start.pos] return None
graphs
def get_successors(self, parent: Node) -> list[Node]: successors = [] for action in delta: pos_x = parent.pos_x + action[1] pos_y = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent) ) return successors
graphs
def retrace_path(self, node: Node | None) -> Path: current_node = node path = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) current_node = current_node.parent path.reverse() return path
graphs
def __init__(self, start, goal): self.fwd_bfs = BreadthFirstSearch(start, goal) self.bwd_bfs = BreadthFirstSearch(goal, start) self.reached = False
graphs
def search(self) -> Path | None: while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: current_fwd_node = self.fwd_bfs.node_queue.pop(0) current_bwd_node = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: self.reached = True return self.retrace_bidirectional_path( current_fwd_node, current_bwd_node ) self.fwd_bfs.target = current_bwd_node self.bwd_bfs.target = current_fwd_node successors = { self.fwd_bfs: self.fwd_bfs.get_successors(current_fwd_node), self.bwd_bfs: self.bwd_bfs.get_successors(current_bwd_node), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(node) if not self.reached: return [self.fwd_bfs.start.pos] return None
graphs
def retrace_bidirectional_path(self, fwd_node: Node, bwd_node: Node) -> Path: fwd_path = self.fwd_bfs.retrace_path(fwd_node) bwd_path = self.bwd_bfs.retrace_path(bwd_node) bwd_path.pop() bwd_path.reverse() path = fwd_path + bwd_path return path
graphs
def __init__(self): self.elements = [] self.set = set()
graphs
def minkey(self): if not self.empty(): return self.elements[0][0] else: return float("inf")
graphs
def empty(self): return len(self.elements) == 0
graphs
def put(self, item, priority): if item not in self.set: heapq.heappush(self.elements, (priority, item)) self.set.add(item) else: # update # print("update", item) temp = [] (pri, x) = heapq.heappop(self.elements) while x != item: temp.append((pri, x)) (pri, x) = heapq.heappop(self.elements) temp.append((priority, item)) for pro, xxx in temp: heapq.heappush(self.elements, (pro, xxx))
graphs
def remove_element(self, item): if item in self.set: self.set.remove(item) temp = [] (pro, x) = heapq.heappop(self.elements) while x != item: temp.append((pro, x)) (pro, x) = heapq.heappop(self.elements) for prito, yyy in temp: heapq.heappush(self.elements, (prito, yyy))
graphs
def top_show(self): return self.elements[0][1]
graphs
def get(self): (priority, item) = heapq.heappop(self.elements) self.set.remove(item) return (priority, item)
graphs
def consistent_heuristic(p: TPos, goal: TPos): # euclidean distance a = np.array(p) b = np.array(goal) return np.linalg.norm(a - b)
graphs
def heuristic_2(p: TPos, goal: TPos): # integer division by time variable return consistent_heuristic(p, goal) // t
graphs
def heuristic_1(p: TPos, goal: TPos): # manhattan distance return abs(p[0] - goal[0]) + abs(p[1] - goal[1])
graphs
def key(start: TPos, i: int, goal: TPos, g_function: dict[TPos, float]): ans = g_function[start] + W1 * heuristics[i](start, goal) return ans
graphs
def do_something(back_pointer, goal, start): grid = np.chararray((n, n)) for i in range(n): for j in range(n): grid[i][j] = "*" for i in range(n): for j in range(n): if (j, (n - 1) - i) in blocks: grid[i][j] = "#" grid[0][(n - 1)] = "-" x = back_pointer[goal] while x != start: (x_c, y_c) = x # print(x) grid[(n - 1) - y_c][x_c] = "-" x = back_pointer[x] grid[(n - 1)][0] = "-" for i in range(n): for j in range(n): if (i, j) == (0, n - 1): print(grid[i][j], end=" ") print("<-- End position", end=" ") else: print(grid[i][j], end=" ") print() print("^") print("Start position") print() print("# is an obstacle") print("- is the path taken by algorithm") print("PATH TAKEN BY THE ALGORITHM IS:-") x = back_pointer[goal] while x != start: print(x, end=" ") x = back_pointer[x] print(x) sys.exit()
graphs
def valid(p: TPos): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True
graphs
def expand_state( s, j, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer, ): for itera in range(n_heuristic): open_list[itera].remove_element(s) # print("s", s) # print("j", j) (x, y) = s left = (x - 1, y) right = (x + 1, y) up = (x, y + 1) down = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(neighbours) and neighbours not in visited: # print("neighbour", neighbours) visited.add(neighbours) back_pointer[neighbours] = -1 g_function[neighbours] = float("inf") if valid(neighbours) and g_function[neighbours] > g_function[s] + 1: g_function[neighbours] = g_function[s] + 1 back_pointer[neighbours] = s if neighbours not in close_list_anchor: open_list[0].put(neighbours, key(neighbours, 0, goal, g_function)) if neighbours not in close_list_inad: for var in range(1, n_heuristic): if key(neighbours, var, goal, g_function) <= W2 * key( neighbours, 0, goal, g_function ): open_list[j].put( neighbours, key(neighbours, var, goal, g_function) )
graphs
def make_common_ground(): some_list = [] for x in range(1, 5): for y in range(1, 6): some_list.append((x, y)) for x in range(15, 20): some_list.append((x, 17)) for x in range(10, 19): for y in range(1, 15): some_list.append((x, y)) # L block for x in range(1, 4): for y in range(12, 19): some_list.append((x, y)) for x in range(3, 13): for y in range(16, 19): some_list.append((x, y)) return some_list
graphs
def multi_a_star(start: TPos, goal: TPos, n_heuristic: int): g_function = {start: 0, goal: float("inf")} back_pointer = {start: -1, goal: -1} open_list = [] visited = set() for i in range(n_heuristic): open_list.append(PriorityQueue()) open_list[i].put(start, key(start, i, goal, g_function)) close_list_anchor: list[int] = [] close_list_inad: list[int] = [] while open_list[0].minkey() < float("inf"): for i in range(1, n_heuristic): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= W2 * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf"): do_something(back_pointer, goal, start) else: _, get_s = open_list[i].top_show() visited.add(get_s) expand_state( get_s, i, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer, ) close_list_inad.append(get_s) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf"): do_something(back_pointer, goal, start) else: get_s = open_list[0].top_show() visited.add(get_s) expand_state( get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer, ) close_list_anchor.append(get_s) print("No path found to goal") print() for i in range(n - 1, -1, -1): for j in range(n): if (j, i) in blocks: print("#", end=" ") elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*", end=" ") else: print("-", end=" ") else: print("*", end=" ") if (j, i) == (n - 1, n - 1): print("<-- End position", end=" ") print() print("^") print("Start position") print() print("# is an obstacle") print("- is the path taken by algorithm")
graphs
def get_parent_position(position: int) -> int: return (position - 1) // 2
graphs
def get_child_left_position(position: int) -> int: return (2 * position) + 1
graphs
def get_child_right_position(position: int) -> int: return (2 * position) + 2
graphs
def __init__(self) -> None: self.heap: list[tuple[T, int]] = [] self.position_map: dict[T, int] = {} self.elements: int = 0
graphs
def __len__(self) -> int: return self.elements
graphs
def __repr__(self) -> str: return str(self.heap)
graphs
def is_empty(self) -> bool: # Check if the priority queue is empty return self.elements == 0
graphs
def push(self, elem: T, weight: int) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight)) self.position_map[elem] = self.elements self.elements += 1 self._bubble_up(elem)
graphs
def extract_min(self) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0, self.elements - 1) elem, _ = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: bubble_down_elem, _ = self.heap[0] self._bubble_down(bubble_down_elem) return elem
graphs
def update_key(self, elem: T, weight: int) -> None: # Update the weight of the given key position = self.position_map[elem] self.heap[position] = (elem, weight) if position > 0: parent_position = get_parent_position(position) _, parent_weight = self.heap[parent_position] if parent_weight > weight: self._bubble_up(elem) else: self._bubble_down(elem) else: self._bubble_down(elem)
graphs
def _bubble_up(self, elem: T) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] curr_pos = self.position_map[elem] if curr_pos == 0: return None parent_position = get_parent_position(curr_pos) _, weight = self.heap[curr_pos] _, parent_weight = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(parent_position, curr_pos) return self._bubble_up(elem) return None
graphs
def _bubble_down(self, elem: T) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] curr_pos = self.position_map[elem] _, weight = self.heap[curr_pos] child_left_position = get_child_left_position(curr_pos) child_right_position = get_child_right_position(curr_pos) if child_left_position < self.elements and child_right_position < self.elements: _, child_left_weight = self.heap[child_left_position] _, child_right_weight = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(child_right_position, curr_pos) return self._bubble_down(elem) if child_left_position < self.elements: _, child_left_weight = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(child_left_position, curr_pos) return self._bubble_down(elem) else: return None if child_right_position < self.elements: _, child_right_weight = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(child_right_position, curr_pos) return self._bubble_down(elem) return None
graphs
def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None: # Swap the nodes at the given positions node1_elem = self.heap[node1_pos][0] node2_elem = self.heap[node2_pos][0] self.heap[node1_pos], self.heap[node2_pos] = ( self.heap[node2_pos], self.heap[node1_pos], ) self.position_map[node1_elem] = node2_pos self.position_map[node2_elem] = node1_pos
graphs
def __init__(self) -> None: self.connections: dict[T, dict[T, int]] = {} self.nodes: int = 0
graphs
def __repr__(self) -> str: return str(self.connections)
graphs