Question 2: Is a graph a tree?
A tree is a graph (V, E) with two special properties:
• Every vertex has at most one incoming edge.
• Either there are no vertices, or there is a vertex with no incoming edges, called the root, from which all other vertices are reachable.
If the second property does not hold, incidentally, the graph is called a forest.
Write an is_tree property that has value True if the graph is a tree, and has value False otherwise.
Implementation of tree test
@title Implementation of tree test
def graph_is_tree(self):
"""Returns True iff the graph is a tree.
#YOUR CODE HERE
Graph.is_tree = property(graph_is_tree)
[] # You may want to write tests here.
# YOUR CODE HERE
[]
#15 points: Tests for tree.
g = Graph(vertices=[1, 2, 3], edges=[(1, 2), (1, 3)])
assert_true(g.is_tree)
g = Graph(vertices=[1, 2, 3], edges=[(1, 2), (2, 3), (1, 3)])
assert_false(g.is_tree)
g = Graph(vertices=[1, 2, 3], edges=[(1, 3), (2, 3)])
assert_false(g.is_tree)
g = Graph(vertices=['a', 'b'], edges=[('a', 'b')])
assert_true(g.is_tree)
g = Graph(vertices=['a', 'b'], edges=[('a', 'b'), ('b', 'a')])
assert_false(g.is_tree)
[] # 15 points: More tests for 'is_tree
g = Graph()
assert_true(g.is_tree)
g = Graph(vertices=['a', 'b', 'c', 'd'], edges=[('a', 'b'), ('c', 'd')])
assert_false(g.is_tree)
g = Graph(vertices=['a', 'b', 'c', 'd'], edges=[('a', 'b'), ('b', 'c'), ('c', 'd')])
assert_true(g.is_tree)