My code below. I am getting an error when trying to create my adjacency matrix. i dont know what i am doing wrong def readMatrix(inputfilename): ''' Returns a two-dimentional array created from the data in the given file. Pre: 'inputfilename' is the name of a text file whose first row contains the number of vertices in a graph and whose subsequent rows contain the rows of the adjacency matrix of the graph. ''
text file
8
0 1 2 3 100 100 100 100
1 0 2 100 3 4 100 100
2 2 0 4 4 100 5 100
3 100 4 0 100 100 4 100
100 3 4 100 0 3 3 3
100 4 100 100 3 0 100 1
100 100 5 4 3 100 0 2
100 100 100 100 3 1 2 0
My code below. I am getting an error when trying to create my adjacency matrix. i dont know what i am doing wrong
def readMatrix(inputfilename):
''' Returns a two-dimentional array created from the data in the given file.
Pre: 'inputfilename' is the name of a text file whose first row contains the
number of vertices in a graph and whose subsequent rows contain the rows of
the adjacency matrix of the graph. '''
# Open the file
f = open(inputfilename, 'r')
# Read the number of vertices from the first line of the file
n = int(f.readline().strip())
# Read the rest of the file stripping off the newline characters and splitting it into
# a list of intger values
rest = f.read().strip().split()
# Create the adjacency matrix
adjMat = []
adjrow=[]
n=rest.split("\n")
a=[]
for i in n:
a.append(i.split(" "))
for i in a:
adjrow=[]
for j in i:
if j=="100":
adjrow.append("INF")
else:
adjrow.append(int(j))
adjMat.append(adjrow)
# Return the matrix
return adjMat
testFile = input("Enter the name of the input file")
graphMatrix = readMatrix(testFile)
graphMatrix
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 2 images