def printmatrix(matrix, iteration, matrixname): print(f"After iteration {iteration},…
- User
def print_matrix(matrix, iteration, matrix_name): print(f"After iteration {iteration}, {matrix_name}:") for row in matrix: formatted_row = ['inf' if x == float('inf') else f'{x:3}' for x in row] print('[{}]'.format(', '.join(formatted_row))) print()
def initialize_matrices(num_vertices, edges): inf = float('inf') D = [[inf if i != j else 0 for i in range(num_vertices)] for j in range(num_vertices)] P = [[0 if i != j else 0 for i in range(num_vertices)] for j in range(num_vertices)]
codefor start, end, weight in edges: D[start][end] = weight P[start][end] = start + 1 return D, Pdef floyd_warshall_with_printing(num_vertices, edges): D, P = initialize_matrices(num_vertices, edges)
codeprint_matrix(D, 0, "D0") print_matrix(P, 0, "P0") for k in range(num_vertices): for i in range(num_vertices): for j in range(num_vertices): if D[i][k] + D[k][j] < D[i][j]: D[i][j] = D[i][k] + D[k][j] P[i][j] = P[k][j] print_matrix(D, k + 1, f"D{k + 1}") print_matrix(P, k + 1, f"P{k + 1}") return D, Pedges = [ (0, 1, 4), (0, 5, 10), (1, 0, 3), (1, 3, 18), (2, 1, 6), (3, 1, 5), (3, 2, 15), (3, 4, 2), (3, 5, 19), (3, 6, 5), (4, 2, 12), (4, 3, 1), (5, 6, 10), (6, 3, 8) ]
num_vertices = 7
final_D, final_P = floyd_warshall_with_printing(num_vertices, edges)
print("Final Distance Matrix:") for row in final_D: formatted_row = ['inf' if x == float('inf') else f'{x:3}' for x in row] print('[{}]'.format(', '.join(formatted_row)))
print("\nFinal Predecessor Matrix:") for row in final_P: formatted_row = [f'{x:3}' for x in row]
print('[{}]'.format(', '.join(formatted_row))) i want the program to print ∞ instead of inf in the matrix - Assistant
To modify your program to print
∞instead ofinfin the matrix, you only need to change the string that represents infinity in theprint_matrixfunction. Here's how the updated version would look:python