Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
class Graph(object):
def __init__(self, size):
self.adjMatrix = [] #creating an empty list
for i in range(size): #for loop for the lngth of the input
self.adjMatrix.append([0 for i in range(size)]) #adding to the list
self.size = size #assigning the variable size
#methods for (1) adding a vertex; (2) adding an edge; (3) removing an edge; and (4) printing the
#matrix should appear here
def addVertex(self, vertNum):
for i in self.adjMatrix: #for loop of the list
length_ = len(i) #assigning the length from each loop
newRow = vertNum - length_ #variable created from input minus the length
for x in range(len(self.adjMatrix)): #for loop of the legnth of the list
for i in range(newRow): #nested for loop of the range of input
self.adjMatrix[x].append(0) #appending the list
for i in self.adjMatrix: #for loop of the list
length_two = len(i) #assinging the second legnth
for y in range(newRow): #for loop of the input
self.adjMatrix.append(0 for i in range(length_two)) #assigning the vertex to the matrix
def addEdge(self, v1, v2): #code to add an edge
if v1 == v2: #the two values are equal
print(("Same vertex %d and %d" % (v1, v2))) #print out the equals vertexs
self.adjMatrix[v1-1][v2-1] = 1 #assigning the first value to be 1
self.adjMatrix[v2-1][v1-1] = 1 #assigning the second vaue to be 1
def removeEdge(self, v1, v2): #code to remove an edge
if self.adjMatrix[v1-1][v2-1] == 0: #if the edge doesn't equal 1
print(("trueNo edge between %d and %d" % (v1, v2))) #print that there is no edge between the two values
return
self.adjMatrix[v1-1][v2-1] = 0 #assigning the first value to be 0
self.adjMatrix[v2-1][v1-1] = 0 #assigning the first value to be 0
def containsEdge(self, v1, v2): #assigning the first value to be 0
return True if self.adjMatrix[v1-1][v2-1] > 0 else False #returning true if the values are greater than 0
def __len__(self):
return self.size #returning the size
def toString(self): #converts the matrix to a string
for row in self.adjMatrix: #for loop of each row
for val in row: #for loop of each value
print(('{:4}'.format(val)), end=' ') #printing the values in the rows
#remember list indexing - this is 1 out, unless we start the matrix at 0 (not a positive integer)
def main(): #funciton containing the inputs
g = Graph(6)
g.addEdge(1, 2)
#prints 1s in top row 3rd and 3rd row 1st
g.addEdge(3,2)
g.addEdge(3,1)
g.addEdge(4,3)
g.addVertex(6)
g.toString()
if __name__ == '__main__':
main()