def testInsert(self): tree2 = BST() tree2.insert(5) tree2.check_ri() self.assertEqual(5, tree2.find(5).key) tree2.insert(3) tree2.check_ri() self.assertEqual(3, tree2.find(3).key) tree2.insert(4) tree2.check_ri() self.assertEqual(4, tree2.find(4).key) tree2.insert(4) tree2.check_ri() self.assertEqual(4, tree2.find(4).key)
class BSTtreeDict(BST): '''A BST-based implementation of a sorted dictionary''' def __init__(self): self._items = BST() def __getitem__(self,key): '''Returns the value associated with key or returns None if key does not exist.''' return self._items.find(key) def __setitem__(self, key, value): self._items.add((key, value)) def __contains__(self,key): return self.__getitem__(key) != None def __str__(self): return str(self._items) def __len__(self): return len(self._items) def __iter__(self): return iter(self._items) def pop(self,key): return self._items.remove(key)
def testFindMin(self): tree2 = BST() self.assertIsNone(tree2.find_min()) tree2.insert(5) self.assertEqual(5, tree2.find(5).key) self.assertEqual(5, tree2.find_min().key) self.assertEqual(4, self.tree1.find_min().key)
class BSTDict(BST): def __init__(self): self._table = BST() def __getitem__(self, key): """Returns the value associated with key or returns None if key does not exist.""" entry = Entry(key, None) result = self._table.find(entry) if result == None: return None else: return result.getValue() def __setitem__(self, key, value): """Inserts an entry with key/value if key does not exist or replaces the existing value with value if key exists.""" entry = Entry(key, value) result = self._table.find(entry) if result == None: self._table.add(entry) else: result.setValue(value) def __contains__(self, key): """Returns True if key in BSTDict otherwise returns False.""" entry = Entry(key, None) result = self._table.find(entry) if result == None: return False else: return True def __len__(self): """Returns the length of the BST Dictionary""" return len(self._table) def __iter__(self): """Iterates through the key/values in the BST""" return iter(self._table) def __str__(self): """Returns unordered string of the dictionary and associated values in tree format.""" return str(self._table)
def bst_search_run(data): # Create a BST bst = BST() # Insert elements for i in xrange(size): bst.insert(i) # Now, get time start = time.clock() # Find elements for i in data: bst.find(i) # Get final time, and store end = time.clock() return { 'structure': 'bst', 'size': size, 'time': end - start, 'comparisons': bst.comparisons }
class TreeSet(object): """A tree-based implementation of a sorted set.""" def __init__(self): self._items = BST() def __contains__(self, item): """Returns True if item is in the set or False otherwise.""" return self._items.find(item) != None def add(self, item): """Adds item to the set if it is not in the set.""" if not item in self: self._items.add(item)
def make_tree(): ''' A helper function to build the tree. The test code depends on this function being available from main. :param: None :returns: A binary search tree ''' my_tree = BST() with open("D:\\UVU\\DavidBennett\\CS2420\\Mod5\\P5\\around-the-world-in-80-days-3.txt", "r") as f: paragraph = f.read() for letter in paragraph: if letter.isalnum(): try: letter_obj = my_tree.find(Pair(letter)) letter_obj.count += 1 except ValueError: my_tree.add(Pair(letter)) # print(my_tree.inorder()) return my_tree
class Test3TenNodesBST(unittest.TestCase): def setUp(self): self.tree = BST() self.keys = random.sample(range(1, 11), 10) def test1_insert_ten_nodes(self): """Inserting ten nodes into a BST should increase its size by ten. (1p)""" for key in self.keys: inserted_node = self.tree.insert(key) self.assertIsInstance( inserted_node, BSTNode, "tree.insert should return an instance of BSTNode, not {0!r}.". format(inserted_node)) self.assertEqual( inserted_node.key, key, "Calling tree.insert({0}) should return a node with the key {0}, not {1}." .format(key, inserted_node.key)) correct_size = len(self.keys) returned_size = len(self.tree) self.assertEqual( correct_size, returned_size, "Calling len on a tree with {0} nodes should return {0}, not {1}". format(correct_size, returned_size)) def test2_find_ten_nodes(self): """All keys which have been inserted should be found by the find method. (1p)""" for key in self.keys: self.tree.insert(key) for key in self.keys: returned_node = self.tree.find(key) self.assertIsNotNone( returned_node, "Calling find for an existing key {0} should return the node holding the key, not None" .format(key)) self.assertEqual( returned_node.key, key, "Calling find for an existing key {0} should return the node holding the key, not {1!r}." .format(key, returned_node))
def test_find(self): """ Tests the bst.find(data) method """ bst = BST() # root does not exist, so no values should exist in tree self.assertFalse(bst.find(1)) bst.insert(50) bst.insert(25) # depth 1 bst.insert(75) # depth 1 bst.insert(13) # depth 2 bst.insert(35) # depth 2 bst.insert(65) # depth 2 bst.insert(80) # depth 2 found = bst.find(50) self.assertEqual(found.data, 50) # 50 exists in tree self.assertIsInstance(bst.find(50), Node) self.assertTrue(bst.find(35)) # 34 exists in tree self.assertFalse(bst.find(100)) # 100 does not exist in tree self.assertFalse(bst.find(-1)) # -1 does not exist in tree self.assertIsInstance(bst.find(-1), bool)
class SymbolTable: def __init__(self): self.__bst = BST() def add(self, value): return self.__bst.add(value) def get(self, value): return self.__bst.find(value) def getRoot(self): return self.__bst.getRoot() def setRoot(self, root): return self.__bst.setRoot(root) def getPosition(self, value): return self.__bst.findPosition(value) def getIndex(self, value): return self.__bst.findIndex(value) def __str__(self): return self.__bst.in_order()
def test_find_empty(): with pytest.raises(ValueError): bst = BST() item = bst.find(Pair('A'))
class Test2EmptyBST(unittest.TestCase): def setUp(self): self.tree = BST() def test1_bst_init_node_class(self): """BSTs are initialized with a node class. (0p).""" self.assertIs( self.tree.BSTNode, BSTNode, "When no node class is specified, the BST should use the class BSTNode as the node class." ) def test2_empty_size(self): """An empty BST has a size equal to zero. (0p)""" tree_size = len(self.tree) self.assertEqual( 0, tree_size, "Calling len on a tree containing no nodes should return 0, not {}" .format(tree_size)) def test3_empty_find(self): """Searching for a key in an empty BST returns None. (0p)""" self.assertIsNone(self.tree.find(1), "Calling find in an empty BST should return None.") def test4_empty_insert(self): """Calling insert on an empty tree returns the inserted node and adds it to the tree. (0p)""" new_key = 1 new_value = "value" inserted_node = self.tree.insert(new_key, new_value) self.assertIsInstance( inserted_node, BSTNode, "tree.insert should return an instance of BSTNode, not {0!r}.". format(inserted_node)) self.assertEqual( inserted_node.key, new_key, "Calling tree.insert({0}, {1}) should return a node with the key {0}, not {2}." .format(new_key, new_value, inserted_node.key)) self.assertIs( inserted_node.value, new_value, "Calling tree.insert({0}, {1}) should return a node with the value {1}, not {2}." .format(new_key, new_value, inserted_node.value)) tree_size = len(self.tree) self.assertEqual( tree_size, 1, "Calling len on a tree containing one key should return 1, not {}". format(tree_size)) def test5_find_one(self): """Calling find for a node which exists should return that node. (1p)""" node = BSTNode(2) node.left = BSTNode(1) node.right = BSTNode(3) self.tree.root = node for node in (node, node.left, node.right): found_node = self.tree.find(node.key) self.assertIs( found_node, node, "If {0!r} exists in tree, calling tree.find({1}) should return that node, not {2!r}" .format(node, node.key, found_node))
class TestBST(unittest.TestCase): def setUp(self): self.bst = BST() def test_insert(self): self.assertEqual([], self.bst.inorder()) self.assertEqual(True, self.bst.insert(5)) self.assertEqual(False, self.bst.insert(5)) self.assertEqual([5], self.bst.inorder()) self.assertEqual(True, self.bst.insert(4)) self.assertEqual([4,5], self.bst.inorder()) self.assertEqual(True, self.bst.insert(7)) self.assertEqual([4,5,7], self.bst.inorder()) def test_find(self): self.assertEqual(False, self.bst.find(5)) self.bst.insert(5) self.assertEqual(True, self.bst.find(5)) self.assertEqual(False, self.bst.find(12)) self.bst.insert(12) self.assertEqual(True, self.bst.find(5)) self.assertEqual(True, self.bst.find(12)) self.bst.remove(12) self.assertEqual(True, self.bst.find(5)) self.assertEqual(False, self.bst.find(12)) self.bst.remove(5) self.assertEqual(False, self.bst.find(5)) def test_remove_1(self): # Empty tree self.assertEqual(False, self.bst.remove(5)) def test_remove_2_1(self): # Value in root # 2.1 Leaf node self.bst.insert(5) self.assertEqual(True, self.bst.remove(5)) self.assertEqual([], self.bst.inorder()) def test_remove_2_2(self): # 2.2 Left chilid only self.bst.insert(5) self.bst.insert(4) self.bst.insert(3) self.assertEqual(5, self.bst.root.data) self.assertEqual([3,4,5], self.bst.inorder()) self.assertEqual(True, self.bst.remove(5)) self.assertEqual([3, 4], self.bst.inorder()) self.assertEqual(4, self.bst.root.data) def test_remove_2_3(self): # 2.3 Right child only self.bst.insert(5) self.bst.insert(7) self.bst.insert(6) self.assertEqual(5, self.bst.root.data) self.assertEqual([5,6,7], self.bst.inorder()) self.assertEqual(True, self.bst.remove(5)) self.assertEqual([6,7], self.bst.inorder()) self.assertEqual(7, self.bst.root.data) def test_remove_2_4(self): # 2.4 Both children self.bst.insert(5) self.bst.insert(4) self.bst.insert(8) self.bst.insert(7) self.bst.insert(6) self.assertEqual(5, self.bst.root.data) self.assertEqual([4,5,6,7,8], self.bst.inorder()) self.assertEqual(True, self.bst.remove(5)) self.assertEqual([4, 6, 7, 8], self.bst.inorder()) self.assertEqual(6, self.bst.root.data) def test_remove_3(self): # Value not in tree self.bst.insert(5) self.bst.insert(4) self.bst.insert(8) self.bst.insert(7) self.bst.insert(6) self.assertEqual(False, self.bst.remove(100)) def test_remove_4(self): # Node is leaf self.bst.insert(5) self.bst.insert(4) self.assertEqual(True, self.bst.remove(4)) self.assertEqual([5], self.bst.inorder()) def test_remove_5(self): # Node has left child only self.bst.insert(5) self.bst.insert(4) self.bst.insert(8) self.bst.insert(7) self.bst.insert(6) self.assertEqual(True, self.bst.remove(8)) self.assertEqual([4,5,6,7], self.bst.inorder()) self.assertEqual(7, self.bst.root.right.data) def test_remove_6(self): # Node has right child only self.bst.insert(5) self.bst.insert(3) self.bst.insert(4) self.assertEqual(True, self.bst.remove(3)) self.assertEqual([4,5], self.bst.inorder()) self.assertEqual(4, self.bst.root.left.data) def test_remove_7(self): # Node has left and right child self.bst.insert(5) self.bst.insert(3) self.bst.insert(4) self.bst.insert(1) self.assertEqual(True, self.bst.remove(3)) self.assertEqual([1,4,5], self.bst.inorder()) self.assertEqual(4, self.bst.root.left.data) def test_preorder(self): self.bst.insert(5) self.bst.insert(4) self.bst.insert(8) self.bst.insert(7) self.bst.insert(6) self.bst.insert(9) self.assertEqual([5,4,8,7,6,9], self.bst.preorder()) def test_postorder(self): self.bst.insert(5) self.bst.insert(4) self.bst.insert(8) self.bst.insert(7) self.bst.insert(6) self.bst.insert(9) self.assertEqual([4,6,7,9,8,5], self.bst.postorder()) def test_inorder(self): self.bst.insert(5) self.bst.insert(4) self.bst.insert(8) self.bst.insert(7) self.bst.insert(6) self.bst.insert(9) self.assertEqual([4,5,6,7,8,9], self.bst.inorder())
class App: bst = BST() def __init__(self, master): # open full screen master.wm_attributes('-zoomed', True) master.update() self.init_ui_elems(master) def init_ui_elems(self, master): master.grid_rowconfigure(0, weight=1) master.grid_columnconfigure(0, weight=1) # Canvas canvas_cont = Frame(master) self.bst_canvas = BSTCanvas(master, canvas_cont) canvas_cont.grid(row=0, sticky="WENS") # Toolbar & text ouput bottom_section = Frame(master, bd=5, relief=RIDGE) bottom_section.grid_columnconfigure(1, weight=3) bottom_section.grid_rowconfigure(0, weight=1) bottom_section.grid(row=1, sticky="WENS") # Toolbar toolbar_cont = Frame(bottom_section) self.toolbar = Toolbar( master, toolbar_cont, on_add_new_node=self.on_add_new_node, on_remove_node=self.on_remove_node, on_show_subtree=self.on_show_subtree, on_get_id=self.on_get_id, on_size_click=self.on_size_click, on_root_click=self.on_root_click, on_min_click=self.on_min_click, on_max_click=self.on_max_click, on_print_click=self.on_print_click, on_reset_click=self.on_reset_click ) toolbar_cont.grid(row=0, column=0, sticky="WENS") # Text output text_output_cont = Frame(bottom_section) text_output_cont.grid_columnconfigure(0, weight=1) text_output_cont.grid_rowconfigure(1, weight=1) text_output_cont.grid(row=0, column=1, sticky="WENS") self.text_output = TextOutput(text_output_cont) def on_size_click(self): self.text_output.println( "Tree size: " + str(self.bst.size) ) def on_root_click(self): self.text_output.println( "Root element: " + str(self.bst.root_key()) ) def on_min_click(self): self.text_output.println( "Min element: " + str(self.bst.min()) ) def on_max_click(self): self.text_output.println( "Max element: " + str(self.bst.max()) ) def on_print_click(self): str_repres= self.bst.to_string() self.text_output.println( 'In-order: ' + str_repres['in_order'] + '\n' + 'Pre-order: ' + str_repres['pre_order'] + '\n' + 'Post-order: ' + str_repres['post_order'] ) def on_reset_click(self): self.bst = BST() self.bst_canvas.draw(self.bst) self.text_output.clear() def on_show_subtree(self, root_key): new_bst = self.bst.subtree(root_key) if new_bst: self.bst = new_bst self.bst_canvas.draw(self.bst) else: self.text_output.println('WARNING: There is no ' + str(root_key) + ' in the tree') def on_add_new_node(self, key): inserted = self.bst.add(key) if inserted: self.bst_canvas.draw(self.bst) else: self.text_output.println('WARNING: Node ' + str(key) + ' was not added since it already exists') def on_remove_node(self, key): removed = self.bst.remove(key) if removed: self.bst_canvas.draw(self.bst) else: self.text_output.println('WARNING: There is no ' + str(key) + ' in the tree') def on_get_id(self, key): id = self.bst.find(key) if id: self.text_output.println('ID of ' + str(key) + ': ' + str(id)) else: self.text_output.println('WARNING: There is no ' + str(key) + ' in the tree')
class BSTTest(unittest.TestCase): def setUp(self): self.tree1 = BST() self.tree1.insert(23) self.tree1.insert(8) self.tree1.insert(4) self.tree1.insert(16) self.tree1.insert(15) self.tree1.insert(42) def testInsert(self): tree2 = BST() tree2.insert(5) tree2.check_ri() self.assertEqual(5, tree2.find(5).key) tree2.insert(3) tree2.check_ri() self.assertEqual(3, tree2.find(3).key) tree2.insert(4) tree2.check_ri() self.assertEqual(4, tree2.find(4).key) tree2.insert(4) tree2.check_ri() self.assertEqual(4, tree2.find(4).key) def testFind(self): tree2 = BST() self.assertIsNone(tree2.find(3)) tree2.insert(4) self.assertIsNone(tree2.find(3)) def testDeleteNodeWithoutChildren(self): d = self.tree1.delete(15) self.tree1.check_ri() self.assertEqual(15, d.key) self.assertIsNone(self.tree1.find(15)) def testDeleteNodeWithOneChild(self): d = self.tree1.delete(16) self.tree1.check_ri() self.assertEqual(16, d.key) self.assertIsNone(self.tree1.find(16)) def testDeleteNodeWithTwoChildren(self): d = self.tree1.delete(8) self.tree1.check_ri() self.assertEqual(8, d.key) self.assertIsNone(self.tree1.find(8)) def testDeleteRoot(self): d = self.tree1.delete(23) self.tree1.check_ri() self.assertEqual(23, d.key) self.assertIsNone(self.tree1.find(23)) self.assertEqual(42, self.tree1.find(42).key) def testDelateLastNode(self): tree2 = BST() tree2.insert(1) deleted = tree2.delete(1) self.assertEqual(1, deleted.key) tree2.check_ri() tree2.insert(2) tree2.check_ri() def testNextLarger(self): self.assertEqual(15, self.tree1.next_larger(8).key) self.assertEqual(23, self.tree1.next_larger(16).key) def testFindMin(self): tree2 = BST() self.assertIsNone(tree2.find_min()) tree2.insert(5) self.assertEqual(5, tree2.find(5).key) self.assertEqual(5, tree2.find_min().key) self.assertEqual(4, self.tree1.find_min().key)
def testFind(self): tree2 = BST() self.assertIsNone(tree2.find(3)) tree2.insert(4) self.assertIsNone(tree2.find(3))