diff --git a/README.MD b/README.MD index eaae067..6d925b8 100644 --- a/README.MD +++ b/README.MD @@ -1,32 +1,19 @@ #Summary -The assignment was to implement a [Weighted Graph](https://codefellows.github.io/sea-python-401d5/assignments/graph_3_weighted.html) -in Python containing the following methods: - - - * g.nodes(): return a list of all nodes in the graph - * g.edges(): return a list of all edges in the graph - * g.add_node(n): adds a new node 'n' to the graph - * g.add_edge(n1, n2): adds a new edge to the graph connecting 'n1' and 'n2', if either n1 or n2 are not already present in the graph, they should be added. - * g.del_node(n): deletes the node 'n' from the graph, raises an error if no such node exists - * g.del_edge(n1, n2): deletes the edge connecting 'n1' and 'n2' from the graph, raises an error if no such edge exists - * g.has_node(n): True if node 'n' is contained in the graph, False if not. - * g.neighbors(n): returns the list of all nodes connected to 'n' by edges, raises an error if n is not in g - * g.adjacent(n1, n2): returns True if there is an edge connecting n1 and n2, False if not, raises an error if either of the supplied nodes are not in g - * g.depth_first_traversal(start): Returns the path list for the entire graph with a depth first traversal. - * g.breadth_first_travers(start): Returns the path list for the entire graph with a breadth first traversal. - + in_order(self): will return a generator that will return the values in the tree using in-order traversal, one at a time. + pre_order(self): will return a generator that will return the values in the tree using pre-order traversal, one at a time. + post_order(self): will return a generator that will return the values in the tree using post_order traversal, one at a time. + breadth_first(self): will return a generator that will return the values in the tree using breadth-first traversal, one at a time. # Coverage: ----------- coverage: platform darwin, python 3.5.2-final-0 ----------- - - -| Name | Stmts | Miss | Cover | -| ----------------------- | ----- | ---- | ----- | -| weighted_graph.py | 78 | 3 | 96% | -| test_weighted_graph.py | 178 | 0 | 100% | -| ----------------------- | --- | -- | ---- | -| TOTAL | 256 | 3 | 98% | +---------- coverage: platform darwin, python 2.7.12-final-0 ---------- +Name Stmts Miss Cover Missing +----------------------------------------------------------- +src/bst.py 121 36 70% 39-40, 73, 92-94, 124, 143, 156-160, 164, 168-182, 186, 190-19 +---------- coverage: platform darwin, python 3.5.2-final-0 ----------- +Name Stmts Miss Cover Missing +----------------------------------------------------------- +src/bst.py 121 36 70% 39-40, 73, 92-94, 124, 143, 156-160, 164, 168-182, 186, 190-198 \ No newline at end of file diff --git a/setup.py b/setup.py index 70142e3..e35bd4b 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ name="data-structures", description="this module will be expanded as we write more data-structures", version=1.1, - author="Ted Callahan and Colin Lamont", + author="Ben Shields and Colin Lamont, initially forked from Ted Callahan's repo, which he worked on with Colin Lamont.", author_email="", license="MIT", package_dir={'': 'src'}, diff --git a/src/bst.py b/src/bst.py new file mode 100644 index 0000000..166ef7e --- /dev/null +++ b/src/bst.py @@ -0,0 +1,198 @@ +"""Module for Binary Search Tree.""" + +from queue_ds import Queue + + +class Node(object): + """Node class.""" + + def __init__(self, value=None, left=None, right=None): + """Init of the Node class.""" + self.value = value + self.left = left + self.right = right + + +class BinarySearchTree(object): + """Binary Search Tree.""" + + """insert(self, val): will insert the value val into the BST. If val is already present, it will be ignored.""" + """search(self, val): will return the node containing that value, else None""" + """size(self): will return the integer size of the BST (equal to the total number of values stored in the tree). It will return 0 if the tree is empty.""" + """depth(self): will return an integer representing the total number of levels in the tree. If there is one value, the depth should be 1, if two values it will be 2, if three values it may be 2 or three, depending, etc.""" + """contains(self, val): will return True if val is in the BST, False if not.""" + """balance(self): will return an integer, positive or negative that represents how well balanced the tree is. Trees which are higher on the left than the right should return a positive value, trees which are higher on the right than the left should return a negative value. An ideally-balanced tree should return 0.""" + """in_order(self): will return a generator that will return the values in the tree using in-order traversal, one at a time.""" + """pre_order(self): will return a generator that will return the values in the tree using pre-order traversal, one at a time.""" + """post_order(self): will return a generator that will return the values in the tree using post_order traversal, one at a time.""" + """breadth_first(self): will return a generator that will return the values in the tree using breadth-first traversal, one at a time.""" + + def __init__(self, if_iter=None): + """Init of the Binary Search Tree class.""" + self.root = None + self.counter = 0 + self.container = [] + if if_iter: + try: + for value in if_iter: + self.insert(value) + except TypeError: + self.insert(if_iter) + self._in_order = self.in_order_trav() + self._pre_order = self.pre_order_trav() + self._post_order = self.post_order_trav() + + def insert(self, val): + """Take a value, inserts into Binary Search Tree at correct placement.""" + if self.root is None: + self.root = Node(val) + self.counter += 1 + self.container.append(val) + + else: + vertex = self.root + while True: + if val > vertex.value: + if vertex.right: + vertex = vertex.right + else: + vertex.right = Node(val) + self.counter += 1 + self.container.append(val) + break + + elif val < vertex.value: + if vertex.left: + vertex = vertex.left + else: + vertex.left = Node(val) + self.counter += 1 + self.container.append(val) + break + else: + break + + def size(self): + """Return size of Binary Search Tree.""" + return self.counter + + def contains(self, val): + """Return True if val is in the BST, False if not.""" + return val in self.container + + def search(self, val): + """Return the node containing that value, else None.""" + vertex = self.root + while vertex: + if val > vertex.value: + if not vertex.right: + return None + vertex = vertex.right + elif val < vertex.value: + if not vertex.left: + return None + vertex = vertex.left + else: + return vertex + return None + + def depth(self): + """ + Return an integer representing the total number of levels in the tree. + + If there is one value, the depth should be 1, if two values it will be 2, + if three values it may be 2 or three, depending, etc. + """ + return self.calc_depth(self.root) + + def calc_depth(self, tree): + """Calculate the depth of the binary search tree recursively.""" + if tree is None: + return 0 + else: + return max(self.calc_depth(tree.right), self.calc_depth(tree.left)) + 1 + + def balance(self): + """ + Return an integer, positive or negative that represents how well balanced the tree is. + + Trees which are higher on the left than the right should return a positive value, + trees which are higher on the right than the left should return a negative value. + An ideally-balanced tree should return 0. + """ + if self.root is None: + return 0 + return self.calc_depth(self.root.right) - self.calc_depth(self.root.left) + + def in_order(self): + """Return.""" + return next(self._in_order) + + def in_order_trav(self): + """Traverse in_order, yielding via generator.""" + vertex = self.root + visited = [] + while (visited or vertex is not None): + + if vertex is not None: + visited.append(vertex) + vertex = vertex.left + else: + vertex = visited.pop() + yield vertex.value + vertex = vertex.right + + def pre_order(self): + """Return.""" + return next(self._pre_order) + + def pre_order_trav(self): + """Traverse pre_order, yielding via generator.""" + vertex = self.root + visited = [] + while (visited or vertex is not None): + if vertex is not None: + yield vertex.value + visited.append(vertex) + vertex = vertex.left + else: + vertex = visited.pop() + vertex = vertex.right + + def post_order(self): + """Return.""" + return next(self._post_order) + + def post_order_trav(self): + """Traverse pre_order, yielding via generator.""" + vertex = self.root + peek_vertex = None + last_vertex = None + visited = [] + while (visited or vertex is not None): + if vertex is not None: + visited.append(vertex) + vertex = vertex.left + else: + peek_vertex = visited[-1] + if peek_vertex.right and peek_vertex.right is not last_vertex: + vertex = peek_vertex.right + else: + yield peek_vertex.value + last_vertex = visited.pop() + + def breadth_first(self): + """Fill in later.""" + return next(self._breadth_first) + + def breadth_first_trav(self): + """Traverse breadth first order, yielding a generator.""" + q = Queue() + q.enqueue(self.root) + while len(q) > 0: + vertex = q.dequeue() + yield vertex.value + if (vertex.left): + q.enqueue(vertex.left) + if (vertex.right): + q.enqueue(vertex.right) diff --git a/src/test_bst.py b/src/test_bst.py new file mode 100644 index 0000000..2eb03de --- /dev/null +++ b/src/test_bst.py @@ -0,0 +1,198 @@ +"""Test Module for Binary Search Tree.""" +from bst import BinarySearchTree +import pytest + +BST_SIMPLE = [8, 10, 3, 14, 13, 1, 6, 7, 4] + + +@pytest.fixture +def filled_bst(): + """Fixture to fill the bst tree with nodes.""" + from bst import BinarySearchTree + new_tree = BinarySearchTree(BST_SIMPLE) + return new_tree + + +def test_insert_5_is_root(): + """Test the insert function.""" + a = BinarySearchTree() + a.insert(5) + assert a.root + + +def test_insert_5_where_root_equals_5(): + """Test the insert funciton.""" + a = BinarySearchTree() + a.insert(5) + assert a.root.value == 5 + + +def test_insert_5_and_10_and_confirm_right(): + """Test the insert function.""" + a = BinarySearchTree() + a.insert(5) + a.insert(10) + assert a.root.right.value == 10 + + +def test_insert_many_numbers(): + """Test the insert function.""" + a = BinarySearchTree() + a.insert(8) + a.insert(10) + a.insert(3) + a.insert(14) + a.insert(13) + a.insert(1) + a.insert(6) + a.insert(7) + a.insert(4) + assert a.root.right.right.left.value == 13 + assert a.root.left.value == 3 + assert a.root.right.right.value == 14 + assert a.root.value == 8 + assert a.root.left.right.left.value == 4 + + +def test_size_returns_size_of_binary_search_tree(): + """Test that the size method returns size of the bst.""" + a = BinarySearchTree() + a.insert(8) + a.insert(10) + a.insert(3) + a.insert(14) + a.insert(13) + a.insert(1) + a.insert(6) + a.insert(7) + a.insert(4) + assert a.size() == 9 + + +def test_binary_search_tree_contains_value(): + """Test that the contains method returns True if value in binary search tree.""" + a = BinarySearchTree() + a.insert(8) + a.insert(10) + a.insert(3) + a.insert(14) + a.insert(13) + a.insert(1) + a.insert(6) + a.insert(7) + a.insert(4) + assert a.contains(4) + + +def test_binary_search_tree_does_not_contain_value(): + """Test that the contains method returns True if value in binary search tree.""" + a = BinarySearchTree() + a.insert(8) + a.insert(10) + a.insert(3) + a.insert(14) + a.insert(13) + a.insert(1) + a.insert(6) + a.insert(7) + a.insert(4) + assert a.contains(100) is False + + +def test_search_5(): + """Test the search function.""" + a = BinarySearchTree() + a.insert(5) + assert a.search(5) == a.root + + +def test_search_10(): + """Test the search function.""" + a = BinarySearchTree() + a.insert(5) + a.insert(10) + assert a.search(10) == a.root.right + + +def test_search_empty(): + """Test the search function.""" + a = BinarySearchTree() + assert a.search(5) is None + + +def test_search_none(): + """Test the search function.""" + a = BinarySearchTree() + a.insert(8) + a.insert(10) + a.insert(3) + a.insert(14) + a.insert(13) + a.insert(1) + a.insert(6) + a.insert(7) + a.insert(4) + assert a.search(100) is None + + +def test_depth_zero(): + """Test the depth function.""" + a = BinarySearchTree() + assert a.depth() == 0 + + +def test_depth_one(): + """Test the depth function.""" + a = BinarySearchTree() + a.insert(8) + assert a.depth() == 1 + + +def test_depth_many(): + """Test the depth function.""" + a = BinarySearchTree() + a.insert(8) + a.insert(10) + a.insert(3) + a.insert(14) + a.insert(13) + a.insert(1) + a.insert(6) + a.insert(7) + a.insert(4) + assert a.depth() == 4 + + +def test_balance(): + """Test the balance function.""" + a = BinarySearchTree() + a.insert(8) + a.insert(10) + a.insert(3) + a.insert(14) + a.insert(13) + a.insert(1) + a.insert(6) + a.insert(7) + assert a.balance() == 0 + + +def test_in_order_traversal_with_generator_first_node_traversed_is_1(filled_bst): + """In-order traversal will fill a list in order.""" + results = [x for x in filled_bst.in_order()] + assert results == [1, 3, 4, 6, 7, 8, 10, 13, 14] + + +def test_in_order_traversal_first_node_traversed_is_1(filled_bst): + """In-order traversal's first value from generator will get a 1.""" + assert filled_bst.in_order() == 1 + + +def test_pre_order_traversal_first_node_traversed_is_8(filled_bst): + """Pre-order traversal will get an 8 first.""" + assert filled_bst.pre_order() == 8 + + +def test_post_order_traversal(filled_bst): + """Post-order traversal.""" + assert filled_bst.post_order() == 1