Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

need help parsing a graph in python I am supposed to implement floyd warshalls a

ID: 3673403 • Letter: N

Question

need help parsing a graph in python

I am supposed to implement floyd warshalls algorithm in python which i did and it works. But the professor wants us it to read from stdin and the way he is inputting it makes in hard for me to implement. it would be read line by line.

input:

This is essentiall saying, for index 0 there is a edge from 0 to 1 with a weight of 28.

I need the format to be put into a graph that is an adjacency matrix using a 2d array:

graph = [[0, 28, inf, 33, inf], [inf, 0, 10, inf, 44], [inf, inf, 0, 50, inf], [inf,inf,inf, 0, 30], [inf,inf,inf,inf, 0]]

inf would represent no edge available so it would be inf = float('inf')

Explanation / Answer

Adjacency Matrix (Graph) in Python:

Below Python code reads user input from console and stores the graph in an adjacency matrix.

# list of lists

adjLists = [ [1,2], [2,3], [4], [4,5], [5], [] ]

# testing

print("Neighbors of vertex 0: ", adjLists[0])

print("Neighbors of vertex 3: ", adjLists[3])

print(" Print all adjacency lists with corresponding vertex")

n = len(adjLists)

for v in range(0,n):

    print(v, ":", adjLists[v])

The output of that program is:

Neighbors of vertex 0: [1, 2]

Neighbors of vertex 3: [4, 5]

Print all adjacency lists with corresponding vertex

0 : [1, 2]

1 : [2, 3]

2 : [4]

3 : [4, 5]

4 : [5]

5 : []