Question

Attached is a simplified undirected Graph ADT class partially implemented using the Edge List structure. Complete the implemeBelow is the Graph file that needs to be modified(using Python3) :

#!/usr/bin/python3

# Simple Vertex class
class Vertex:
""" Lightweight vertex structure for a graph.
Vertices can have the following labels:
UNEXPLORED
VISITED
Assuming the element of a vertex is string type
"""
__slots__ = '_element', '_label'

def __init__(self, element, label="UNEXPLORED"):
""" Constructor. """
self._element = element
self._label = label

def element(self):
""" Return element associated with this vertex. """
return self._element

def getLabel(self):
""" Get label assigned to this vertex. """
return self._label

def setLabel(self, label):
""" Set label after the vertex has been created. """
self._label = label

def __str__(self):
""" Used when printing this object. """
return "(%s, %s)" % (self._element,self._label)

# Simple Edge class
class Edge:
""" Lightweight edge structure for a graph.
Edges can have the following labels:
UNEXPLORED
DISCOVERY
BACK
"""
__slots__ = '_origin', '_destination','_element', '_label'

def __init__(self, u, v, element = None,label = "UNEXPLORED"):
""" Constructor. Note that u and v are Vertex objects. """
self._origin = u
self._destination = v
self._element = element
self._label = label

def getLabel(self):
""" Get label assigned to this edge. """
return self._label

def setLabel(self, label):
""" Set label after the edge has been created. """
self._label = label

def endpoints(self):
""" Return (u,v) tuple for source and destination vertices. """
return (self._origin, self._destination)

def isIncident(self, v):
""" Return True if vertex v is incident upon this edge, else False. """
return v == self._origin or v == self._destination

def isEndponts(self, u, v):
""" Return True if both vertics u and v are incident upon this edge, else False. """
return self.isIncident(u) and self.isIncident(v)
  
def opposite(self, v):
""" Return the vertex that is opposite v on this edge. """
if not isinstance(v, Vertex):
raise TypeError('v must be a Vertex')
if v not in [self._destination, self._origin]:
raise ValueError('v not incident to edge')
return self._destination if v is self._origin else self._origin

def __str__(self):
""" Used when printing this object. """
return "(%s, %s, %s)" % (self._origin._element,self._destination._element,self._label)

class Graph:
""" Partial Graph ADT represented by an edge list structure."""
  
#---- Graph implementation -------------------------
__slots__ = '_edges', '_vertices'

def __init__(self):
self._edges = []
self._vertices = []

#-- Public methods
def edges(self):
""" Return all edges of the graph. """
# ... Implement this (1)
return [] #replace to your one code

def edgeCount(self):
""" Return the number of edges in the graph. """
# ... Implement this (2)
return [] #replace to your one code

def vertices(self):
""" Return all vertices of the graph. """
# ... Implement this (3)
return [] #replace to your one code

def vertexCount(self):
""" Return the number of vertices in the graph. """
# ... Implement this (4)
return [] #replace to your one code

def getEdge(self, v1, v2):
""" Return the edge with vertices v1 to v2, or None if not adjacent. """
# ... Implement this (5)
return None #replace to your one code

def getVertexByValue(self, e):
""" Return the vertex that has element of value e. """
# ... Implement this (6)
return None #replace to your one code
def incidentEdges(self, v):
""" Return a collection of all edges that are incident to vertex v in the graph. """
# ... Implement this (7)
return [] #replace to your one code

def print(self):
""" Print the edge list with the format:
"""
print("Edge List:" )
for e in self.edges():
print(e)
print()

def insert_vertex(self, x=None):
"""Insert and return a new Vertex with element x."""
v = Vertex(x)
self._vertices.append(v)
return v
  
def insert_edge(self, u, v, x=None):
"""Insert and return a new Edge from u to v with auxiliary element x.

Raise a ValueError if u and v are not vertices of the graph.
Raise a ValueError if u and v are already adjacent.
"""
if self.getEdge(u, v) is not None: # includes error checking
raise ValueError('u and v are already adjacent')
e = Edge(u, v, x)
self._edges.append(e)
  
def DFS(g):
# Implement the depth-first search algorithm from the class notes.
# Collect the discovered edges that form the DFS tree of 'g' and return the collection
# ... Implement this (8)
return [] #replace to your one code


#-- Main method
v_elements = ["A","B","C","D","E"]
g = Graph()
for v in range(5):
g.insert_vertex(v_elements[v])
  
g.insert_edge(g.getVertexByValue("A"),g.getVertexByValue("B"))
g.insert_edge(g.getVertexByValue("A"),g.getVertexByValue("C"))
g.insert_edge(g.getVertexByValue("B"),g.getVertexByValue("C"))
g.insert_edge(g.getVertexByValue("B"),g.getVertexByValue("D"))
g.insert_edge(g.getVertexByValue("B"),g.getVertexByValue("E"))
g.insert_edge(g.getVertexByValue("C"),g.getVertexByValue("D"))
g.insert_edge(g.getVertexByValue("C"),g.getVertexByValue("E"))

# Print all edges
print("Edges:", g.edgeCount())
for e in g.edges():
print(e)
print()

# Print all vertices
print("Vertices:", g.vertexCount())
for v in g.vertices():
print(v)
print()

# Print the actual graph (in matrix form)
g.print()
print()

# Call DFS on g, to get the discovery edges
discovery = DFS(g)
print("DFS edges:")
for e in discovery:
print(e)
print()

# Determine whether the graph is connected
# ... Implement this (9)
print("Graph is connected:", False) #replace to your one code

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PYTHON CODE:

#!/usr/bin/python3

# Simple Vertex class
class Vertex:
""" Lightweight vertex structure for a graph.
Vertices can have the following labels:
UNEXPLORED
VISITED
Assuming the element of a vertex is string type
"""
__slots__ = '_element', '_label'
  
def __init__(self, element, label="UNEXPLORED"):
""" Constructor. """
self._element = element
self._label = label
  
def element(self):
""" Return element associated with this vertex. """
return self._element
  
def getLabel(self):
""" Get label assigned to this vertex. """
return self._label
  
def setLabel(self, label):
""" Set label after the vertex has been created. """
self._label = label
  
def __str__(self):
""" Used when printing this object. """
return "(%s, %s)" % (self._element,self._label)

# Simple Edge class
class Edge:
""" Lightweight edge structure for a graph.
Edges can have the following labels:
UNEXPLORED
DISCOVERY
BACK
"""
__slots__ = '_origin', '_destination','_element', '_label'
  
def __init__(self, u, v, element = None,label = "UNEXPLORED"):
""" Constructor. Note that u and v are Vertex objects. """
self._origin = u
self._destination = v
self._element = element
self._label = label
  
def getLabel(self):
""" Get label assigned to this edge. """
return self._label
  
def setLabel(self, label):
""" Set label after the edge has been created. """
self._label = label
  
def endpoints(self):
""" Return (u,v) tuple for source and destination vertices. """
return (self._origin, self._destination)
  
def isIncident(self, v):
""" Return True if vertex v is incident upon this edge, else False. """
return v == self._origin or v == self._destination
  
def isEndponts(self, u, v):
""" Return True if both vertics u and v are incident upon this edge, else False. """
return self.isIncident(u) and self.isIncident(v)
  
def opposite(self, v):
""" Return the vertex that is opposite v on this edge. """
if not isinstance(v, Vertex):
raise TypeError('v must be a Vertex')
if v not in [self._destination, self._origin]:
raise ValueError('v not incident to edge')
return self._destination if v is self._origin else self._origin
  
def __str__(self):
""" Used when printing this object. """
return "(%s, %s, %s)" % (self._origin._element,self._destination._element,self._label)

class Graph:
""" Partial Graph ADT represented by an edge list structure."""
  
#---- Graph implementation -------------------------
__slots__ = '_edges', '_vertices'
  
def __init__(self):
self._edges = []
self._vertices = []
  
#-- Public methods
def edges(self):
""" Return all edges of the graph. """
# ... Implement this (1)
#return [] #replace to your one code
return self._edges
  
def edgeCount(self):
""" Return the number of edges in the graph. """
# ... Implement this (2)
#return [] #replace to your one code
return len(self._edges)
  
def vertices(self):
""" Return all vertices of the graph. """
# ... Implement this (3)
#return [] #replace to your one code
return self._vertices
  
def vertexCount(self):
""" Return the number of vertices in the graph. """
# ... Implement this (4)
#return [] #replace to your one code
return len(self._vertices)
  
def getEdge(self, v1, v2):
""" Return the edge with vertices v1 to v2, or None if not adjacent. """
# ... Implement this (5)
#return None #replace to your one code
for EDGE in self._edges:
if EDGE.isEndponts(v1,v2):
return EDGE
return None
  
def getVertexByValue(self, e):
""" Return the vertex that has element of value e. """
# ... Implement this (6)
for VERTEX in self._vertices:
if VERTEX.element()==e:
return VERTEX
return None
#replace to your one code
  
def incidentEdges(self, v):
""" Return a collection of all edges that are incident to vertex v in the graph. """
# ... Implement this (7)
INCI_EDGES=[]
for EDGES in self._edges:
if(EDGES.isIncident(v)):
INCI_EDGES.append(EDGES)
return INCI_EDGES #replace to your one code
  
def print(self):
""" Print the edge list with the format:
"""
print("Edge List:" )
for e in self.edges():
print(e)
print()
  
def insert_vertex(self, x=None):
"""Insert and return a new Vertex with element x."""
v = Vertex(x)
self._vertices.append(v)
return v
  
def insert_edge(self, u, v, x=None):
"""Insert and return a new Edge from u to v with auxiliary element x.
  
Raise a ValueError if u and v are not vertices of the graph.
Raise a ValueError if u and v are already adjacent.
"""
if self.getEdge(u, v) is not None: # includes error checking
raise ValueError('u and v are already adjacent')
e = Edge(u, v, x)
self._edges.append(e)

def DFS_utility(g,v):
v.setLabel("VISITED")
for edge in g.incidentEdges(v):
if (edge.getLabel()=="UNEXPLORED"):
next_vert=edge.opposite(v)
if(next_vert.getLabel()=="UNEXPLORED"):
edge.setLabel("DISCOVERY")
DFS_utility(g,next_vert)
else:
edge.setLabel("BACK")
  
def DFS(g):
# Implement the depth-first search algorithm from the class notes.
# Collect the discovered edges that form the DFS tree of 'g' and return the collection
# ... Implement this (8)
v=g.vertices()[0];
DFS_utility(g,v);
Discovery_edge_list=[]
for edge in g.edges():
if(edge.getLabel()=="DISCOVERY"):
Discovery_edge_list.append(edge);
return Discovery_edge_list
#return [] #replace to your one code


#-- Main method
v_elements = ["A","B","C","D","E"]
g = Graph()
for v in range(5):
g.insert_vertex(v_elements[v])
  
g.insert_edge(g.getVertexByValue("A"),g.getVertexByValue("B"))
g.insert_edge(g.getVertexByValue("A"),g.getVertexByValue("C"))
g.insert_edge(g.getVertexByValue("B"),g.getVertexByValue("C"))
g.insert_edge(g.getVertexByValue("B"),g.getVertexByValue("D"))
g.insert_edge(g.getVertexByValue("B"),g.getVertexByValue("E"))
g.insert_edge(g.getVertexByValue("C"),g.getVertexByValue("D"))
g.insert_edge(g.getVertexByValue("C"),g.getVertexByValue("E"))

# Print all edges
print("Edges:", g.edgeCount())
for e in g.edges():
print(e)
print()

# Print all vertices
print("Vertices:", g.vertexCount())
for v in g.vertices():
print(v)
print()

# Print the actual graph (in matrix form)
g.print()
print()

# Call DFS on g, to get the discovery edges
discovery = DFS(g)
print("DFS edges:")
for e in discovery:
print(e)
print()

# Determine whether the graph is connected
# ... Implement this (9)
isconnec=True
for vert in g.vertices():
if(vert.getLabel()=="UNEXPLORED"):
isconnec=False
print("Graph is connected:", isconnec) #replace to your one code

CODE SNAPSHOT:

1 #!/usr/bin/python3 3 # Simple Vertex class 4. class Vertex: Lightweight vertex structure for a graph. Vertices can have

35 - class Edge: Lightweight edge structure for a graph. 37 Edges can have the following labels: UNEXPLORED DISCOVERY BACK

64 return selt.isIncident u) and self.isIncident v 70 71 72 73 74 def opposite(self, v): Return the vertex that is opposi

105 106 107 108 def vertices(self): Return all vertices of the graph. # ... Implement this (3) #return [] #replace to y

151 156 140 for EDGES in self._edges: 141 if(EDGES.isIncident(v)): 142 INCI_EDGES. append(EDGES) 143 return INCI_EDGES #repla

174 179 Search algorithm from the otasg nanalo return th 183 next_vert=edge.opposite(v) 175 if(next_vert.getLabel() == UNEXP

203 g.insert_edge(g.getVertexByValue(B),g.getVertexByValue(C)) 204 g.insert_edge(g.getVertexByValue(B),g.getVertexByVal

OUTPUT SNAPSHOT:

Edges: 7 (A, B, UNEXPLORED) (A, C, UNEXPLORED) (B, C, UNEXPLORED) (B, D, UNEXPLORED) (B, E, UNEXPLORED) (C, D, UNEXPLORED) (C

Add a comment
Know the answer?
Add Answer to:
Below is the Graph file that needs to be modified(using Python3) : #!/usr/bin/python3 # Simple Vertex...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Show the operation of depth-first search (DFS) on the graph of Figure 1 starting from vertex...

    Show the operation of depth-first search (DFS) on the graph of Figure 1 starting from vertex q. Always process vertices in alphabetical order. Show the discovery and finish times for each vertex, and the classification of each edge. (b) A depth-first forest classifies the edges of a graph into tree, back, forward, and cross edges. A breadth-first search (BFS) tree can also be used to classify the edges reachable from the source of the search into the same four categories....

  • from collections import defaultdict    # This class represents a directed graph using # adjacency list...

    from collections import defaultdict    # This class represents a directed graph using # adjacency list representation class Graph:        # Constructor     def __init__(self):            # default dictionary to store graph         self.graph = defaultdict(list)        # function to add an edge to graph     def addEdge(self,u,v):         self.graph[u].append(v)        # Function to print a BFS of graph     def BFS(self, s):            # Mark all the vertices as not visited         visited = [False] * (len(self.graph))            # Create a queue for BFS         queue...

  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given. Write a driver program, which reads input file mediumG.txt as an undirected graph and runs the depth-first search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to ‘v’: list of all the vertices traversed to...

  • need help filling in the code def prim(G): Use Prim's algorithm to find a MST for the graph G … # Initialize tree T with a single vertex and no edges v = next(iter( )) # while the vertex set of T...

    need help filling in the code def prim(G): Use Prim's algorithm to find a MST for the graph G … # Initialize tree T with a single vertex and no edges v = next(iter( )) # while the vertex set of T is smaller than the v+tex set of G, # (i.e. while the vertex set of T is a proper subset of the vertex set of G), find the edge e with minimum weight so that # Tte is...

  • Let G = (V;E) be an undirected and unweighted graph. Let S be a subset of the vertices. The graph...

    Let G = (V;E) be an undirected and unweighted graph. Let S be a subset of the vertices. The graph induced on S, denoted G[S] is a graph that has vertex set S and an edge between two vertices u, v that is an element of S provided that {u,v} is an edge of G. A subset K of V is called a killer set of G if the deletion of K kills all the edges of G, that is...

  • Consider the java Graph class below which represents an undirected graph in an adjacency list. How...

    Consider the java Graph class below which represents an undirected graph in an adjacency list. How would you add a method to delete an edge from the graph? // Exercise 4.1.3 (Solution published at http://algs4.cs.princeton.edu/) package algs41; import stdlib.*; import algs13.Bag; /** * The <code>Graph</code> class represents an undirected graph of vertices * named 0 through V-1. * It supports the following operations: add an edge to the graph, * iterate over all of the neighbors adjacent to a vertex....

  • The DFSGraph uses a time attribute to note when a vertex is first encountered (discovery attribute)...

    The DFSGraph uses a time attribute to note when a vertex is first encountered (discovery attribute) in the depth-first search (dfs) and when a vertex is backtracked thro (finish attribute). Consider the prerequisite graph for the courses in Bob's Computer Science minor. CS 1410 CS 3470 CS 4400) CS 1510 CS 1510) CS 1520 C$ 1520) CS 2530 S 2530 from graph import Graph class DFSGraph(Graph): definit__(self): super() . _init_0 self. time = 0 def dfs (self): for aVertex in...

  • (a) Sketch a 2D vertex-edge graph of the square pyramid shown below. Euler's formula: v+f=e+2 (b)...

    (a) Sketch a 2D vertex-edge graph of the square pyramid shown below. Euler's formula: v+f=e+2 (b) The square pyramid has 5 faces and 5 vertices. How many edges does it have? (c) Label each geometric solid as possible or impossible. 8 vertices, 14 edges, 6 faces 7 vertices, 12 edges, 7 faces

  • 1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing...

    1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing the nodes added to the min spanning tree and the order they are added. Using Python. Starter code: from collections import deque class Edge: def __init__(self, endIndex, next = None): self.endIndex = endIndex self.next = next class Node: def __init__(self, name): self.name = name self.visited = False self.connects = None class Graph: def __init__(self): self.nodeList = [] self.size = 20...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT