Question: Write a function for Prim's MST algorithm. Any implementation is acceptable. The output should include both the set of edges in and the total cost

Write a function for Prim's MST algorithm. Any implementation is acceptable. The output should include both the set of edges in and the total cost of the MST.

python code, please use below function!

def read_graph(file_name): with open(file_name, 'r') as file: graph = [] lines = file.readlines() for line in lines: costs = line.strip().split(' ') row = [] for cost in costs: row.append(int(cost)) graph.append(row) return graph def desc_graph(graph): num_vertices = len(graph) message = '' message += 'Number of vertices = ' + str(num_vertices) + ' ' non_zero = 0 for i in range(num_vertices): for j in range(num_vertices): if graph[i][j] > 0: non_zero += 1 num_edges = int(non_zero / 2) message += 'Number of edges = ' + str(num_edges) + ' ' message += 'Symmetric = ' + str(is_symmetric(graph)) + ' ' return message def is_symmetric(graph): num_vertices = len(graph) for i in range(num_vertices): for j in range(num_vertices): if graph[i][j] != graph[j][i]: return False return True def print_graph(graph, sep=' '): str_graph = '' for row in range(len(graph)): str_graph += sep.join([str(c) for c in graph[row]]) + ' ' return str_graph
def analyze_graph(file_name): graph = read_graph(file_name) output_file_name = file_name[0:-4 + len(file_name)] + '_report.txt' with open(output_file_name, 'w') as output_file: output_file.write('Analysis of graph: ' + file_name + ' ') str_graph = print_graph(graph) output_file.write(str_graph + ' ') graph_descrip = desc_graph(graph) output_file.write(graph_descrip + ' ') dfs_traversal = dfs(graph) bfs_traversal = bfs_wrapper(graph) prim_traversal = primMST(graph) output_file.write('dfs traversal: ' + str(dfs_traversal) + ' ') output_file.write('bfs traversal: ' + str(bfs_traversal) + ' ') output_file.write('prim_traversal: ' + str(prim_traversal) + ' ') def main(): mypath = "C:\\Users\\heten\\PycharmProjects\\assignment4" files = [f for f in listdir(mypath) if isfile(join(mypath, f))] for file in files: if file[0:5] == 'graph' and file.find('_report') < 0: analyze_graph(file)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!