fix this code import random import sys import networkx as nx import matplotlib.pyplot as…
- User
fix this code
import random import sys import networkx as nx import matplotlib.pyplot as plt
n = 5 sparsity = 50
def congestion(cost_mat, G): for i in range(n): for j in range(i): change = random.randint(-1, 1) cost_mat[i][j] += (cost_mat[i][j] // 10) * change if cost_mat[i][j] < 0: cost_mat[i][j] = 0 cost_mat[j][i] = cost_mat[i][j] G.edges[i, j]['weight'] = cost_mat[i][j] G.edges[j, i]['weight'] = cost_mat[i][j] draw_graph(G)
def dijkstra(cost_mat, src, G): dist = [sys.maxsize] * n sptSet = [False] * n dist[src] = 0
codefor _ in range(n - 1): u = min_distance(dist, sptSet) sptSet[u] = True congestion(cost_mat, G) # Update cost matrix after expanding a node for v in range(n): if not sptSet[v] and cost_mat[u][v] and dist[u] != sys.maxsize and dist[u] + cost_mat[u][v] < dist[v]: dist[v] = dist[u] + cost_mat[u][v] return distdef min_distance(dist, sptSet): min_val = sys.maxsize min_index = -1
codefor v in range(n): if not sptSet[v] and dist[v] <= min_val: min_val = dist[v] min_index = v return min_indexdef generate_cost_matrix(): cost_mat = [[0] * n for _ in range(n)] for i in range(n): for j in range(i + 1, n): if random.randint(0, 100) < sparsity: cost = random.randint(1, 100) cost_mat[i][j] = cost cost_mat[j][i] = cost return cost_mat
def draw_graph(G): pos = nx.spring_layout(G) plt.figure() nx.draw(G, pos, with_labels=True) edge_labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) plt.show()
def main(): cost_mat = generate_cost_matrix() G = nx.Graph() G.add_nodes_from(range(n)) for i in range(n): for j in range(i + 1, n): if cost_mat[i][j] != 0: G.add_edge(i, j, weight=cost_mat[i][j])
codesrc = random.randint(0, n - 1) dest = random.randint(0, n - 1) while dest == src: dest = random.randint(0, n - 1) print(f"Source: {src}, Destination: {dest}") dist = dijkstra(cost_mat, src, G) print("Vertex\tDistance from Source") for i in range(n): print(f"{i}\t{dist[i]}") - Assistant
- User
Source: 0
KeyError Traceback (most recent call last) in <cell line: 87>() 86 87 if name == "main": ---> 88 main()
3 frames /usr/local/lib/python3.10/dist-packages/networkx/classes/coreviews.py in getitem(self, key) 51 52 def getitem(self, key): ---> 53 return self._atlas[key] 54 55 def copy(self):
KeyError: 0
- Assistant
- User
- Assistant