This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).

Challenge Notebook

Constraints

  • Is the graph directed?
    • Yes
  • Do the edges have weights?
    • Yes

Test Cases

Input:

  • add_edge(source, destination, weight)
graph.add_edge(0, 1, 5)
graph.add_edge(0, 5, 2)
graph.add_edge(1, 2, 3)
graph.add_edge(2, 3, 4)
graph.add_edge(3, 4, 5)
graph.add_edge(3, 5, 6)
graph.add_edge(4, 0, 7)
graph.add_edge(5, 4, 8)
graph.add_edge(5, 2, 9)

Result:

  • source and destination nodes within graph are connected with specified weight.

Note:

  • We'll be using an OrderedDict to make the outputs more consistent and simplify our testing.
  • Graph will be used as a building block for more complex graph challenges.

Algorithm

Refer to the Solution Notebook. If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start.

Code


In [ ]:
from collections import OrderedDict


class Node:

    def __init__(self, id):
        # TODO: Implement me
        self.adjacent = OrderedDict()  # key = node, val = weight

    def __str__(self):
        return str(self.id)


class Graph:

    def __init__(self):
        # TODO: Implement me
        self.nodes = OrderedDict()  # key = node id, val = node

    def add_node(self, id):
        # TODO: Implement me
        pass

    def add_edge(self, source, dest, weight=0):
        # TODO: Implement me
        pass

Unit Test

The following unit test is expected to fail until you solve the challenge.


In [ ]:
# %load test_graph.py
from nose.tools import assert_equal


class TestGraph(object):

    def test_graph(self):
        graph = Graph()
        for id in range(0, 6):
            graph.add_node(id)
        graph.add_edge(0, 1, 5)
        graph.add_edge(0, 5, 2)
        graph.add_edge(1, 2, 3)
        graph.add_edge(2, 3, 4)
        graph.add_edge(3, 4, 5)
        graph.add_edge(3, 5, 6)
        graph.add_edge(4, 0, 7)
        graph.add_edge(5, 4, 8)
        graph.add_edge(5, 2, 9)

        assert_equal(graph.nodes[0].adjacent[graph.nodes[1]], 5)
        assert_equal(graph.nodes[0].adjacent[graph.nodes[5]], 2)
        assert_equal(graph.nodes[1].adjacent[graph.nodes[2]], 3)
        assert_equal(graph.nodes[2].adjacent[graph.nodes[3]], 4)
        assert_equal(graph.nodes[3].adjacent[graph.nodes[4]], 5)
        assert_equal(graph.nodes[3].adjacent[graph.nodes[5]], 6)
        assert_equal(graph.nodes[4].adjacent[graph.nodes[0]], 7)
        assert_equal(graph.nodes[5].adjacent[graph.nodes[4]], 8)
        assert_equal(graph.nodes[5].adjacent[graph.nodes[2]], 9)

        print('Success: test_graph')


def main():
    test = TestGraph()
    test.test_graph()


if __name__ == '__main__':
    main()

Solution Notebook

Review the Solution Notebook for a discussion on algorithms and code solutions.