def test_key02(self):
     key_list = [
         (90, '이상해씨'),
         (50, '이상해풀'),
         (150, '이상해꽃'),
         (20, '파이리'),
         (75, '리자드'),
         (95, '리자몽'),
         (175, '꼬부기'),
         (5, '어니부기'),
         (25, '거북왕'),
         (66, '캐터피'),
         (80, '단데기'),
         (92, '버터플'),
         (111, '뿔충이'),
         (166, '딱충이'),
         (200, '독침붕')
     ]
     bst = BinarySearchTree()
     for key, value in key_list:
         bst.insert_node(key, value)
     self.assertTrue(is_bst(bst.get_root()))
     for key, value in key_list:
         temp_bst = copy.deepcopy(bst)
         temp_bst.delete_node(key)
         self.assertTrue(is_bst(bst.get_root()))
Beispiel #2
0
def main():
    target_list = [
        (8, '여덟'),
        (2, '둘'),
        (9, '아홉'),
        (3, '셋'),
        (6, '여섯'),
        (5, '다섯'),
        (4, '넷'),
        (1, '하나'),
        (7, '일곱')
    ]
    print(target_list)

    bst = BinarySearchTree()
    for key, value in target_list:
        bst.insert_node(key, value)
    bst.print_bst()

    for key, value in target_list:
        copied_bst = copy.deepcopy(bst)
        print('Delete {0}'.format(key))
        copied_bst.delete_node(key)
        copied_bst.print_bst()
        print('Is Binary Search Tree? {0}'.format(is_bst(copied_bst.get_root())))
 def test_key01(self):
     key_list = [8, 3, 10, 1, 6, 4, 7, 14, 13]
     bst = BinarySearchTree()
     for key in key_list:
         bst.insert_node(key, None)
     self.assertTrue(is_bst(bst.get_root()))
     for key in key_list:
         temp_bst = copy.deepcopy(bst)
         temp_bst.delete_node(key)
         self.assertTrue(is_bst(bst.get_root()))
 def test_key04(self):
     key_list = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
     bst = BinarySearchTree()
     for key in key_list:
         bst.insert_node(key, None)
     self.assertTrue(is_bst(bst.get_root()))
     for key in key_list:
         temp_bst = copy.deepcopy(bst)
         temp_bst.delete_node(key)
         self.assertTrue(is_bst(bst.get_root()))
 def test_max(self):
     """
     test the following binary search tree
      1
       \
        2
         \
          3
     """
     bst = BinarySearchTree()
     bst.insert(1)
     bst.insert(2)
     expected_max = bst.insert(3)
     self.assertEqual(bst.max(), expected_max)
    def test_insert(self):
        """
        test the following binary search tree
              4
             / \
            /   \
           2     6
          / \   / \
         1   3  5  7
        """
        bst = BinarySearchTree()
        root = bst.insert(4)
        self.assertEqual(bst.root, root)

        left_child = bst.insert(2)
        self.assertEqual(bst.root.left_child, left_child)
        left_child_left_child = bst.insert(1)
        self.assertEqual(bst.root.left_child.left_child, left_child_left_child)
        left_child_right_child =bst.insert(3)
        self.assertEqual(bst.root.left_child.right_child, left_child_right_child)

        right_child = bst.insert(6)
        self.assertEqual(bst.root.right_child, right_child)
        right_child_left_child = bst.insert(5)
        self.assertEqual(bst.root.right_child.left_child, right_child_left_child)
        right_child_right_child = bst.insert(7)
        self.assertEqual(bst.root.right_child.right_child, right_child_right_child)
 def test_min(self):
     """
     test the following binary search tree
          3
         /
        2
       /
      1
     """
     bst = BinarySearchTree()
     bst.insert(3)
     bst.insert(2)
     expected_min = bst.insert(1)
     self.assertEqual(bst.min(), expected_min)
 def test_prev_node_of_min(self):
     """
     test the following binary search tree
      1
       \
        2
         \
          3 <-- get next node of 3
     """
     bst = BinarySearchTree()
     bst.insert(1)
     bst.insert(2)
     node = bst.insert(3)
     self.assertEqual(bst.next(node), None)
 def test_prev_node_of_min(self):
     """
     test the following binary search tree
          3
         /
        2
       /
      1 <-- get prev node of 1
     """
     bst = BinarySearchTree()
     bst.insert(3)
     bst.insert(2)
     node = bst.insert(1)
     self.assertEqual(bst.prev(node), None)
 def test_next_node_has_right_subtree(self):
     """
     test the following binary search tree
      1 <-- get next node of 1
       \
        3
       / \
      2   4
     """
     bst = BinarySearchTree()
     node = bst.insert(1)
     bst.insert(3)
     expected_next = bst.insert(2)
     bst.insert(4)
     self.assertEqual(bst.next(node), expected_next)
 def test_prev_node_has_no_left_subtree(self):
     """
     test the following binary search tree
          4
         /
        1
         \
          3
         /
        2 <-- get prev node of 2
     """
     bst = BinarySearchTree()
     bst.insert(4)
     expected_prev = bst.insert(1)
     bst.insert(3)
     node = bst.insert(2)
     self.assertEqual(bst.prev(node), expected_prev)
class MemoryCache(object):
	def __init__(self, size=100, capacity=120):
		self.size = size
		self.capacity = capacity
		self.current_size = 0
		self.stats_init()
		self.tree = BinarySearchTree()

	def stats_init(self):
		self.hit = 0
		self.miss = 0

	def set(self, key, value):
		self.tree.insert_node(key, value)
		self.current_size += 1
		if self.current_size > self.capacity:
			self.shrink()

	def get(self, key):
		val = self.tree.find(key)
		if val:
			self.hit += 1
		else:
			self.miss += 1
			return None
		return val

	def stats(self):
		return "\nhit: %s\nmiss: %s\nhit_ratio: %s\n" %(self.hit, self.miss, \
			float(self.hit) / (self.miss+self.hit))

	def shrink(self):
		for i in range(1,self.current_size - self.size):
			result = self.tree.shrink()
			while not result:
				result = self.tree.shrink()
Beispiel #13
0
def factor1(target):
    start_time = time()
    num_states = 1

    if not isinstance(target, IntegerBase2):
        target = IntegerBase2(target)

    key_func = partial(lambda x, target: target.as_int - x.as_int, target=target)
    frontier = BinarySearchTree(key_func)

    num_digits = target_to_max_factor_num_digits(target, 0)
    for i, j in itertools.combinations_with_replacement(xrange(BASE), 2):
        p_digits = [0 for _ in xrange(num_digits)]
        q_digits = [0 for _ in xrange(num_digits)]
        p_digits[-1] = i
        q_digits[-1] = j
        _prod = Product(p_digits, q_digits)
        frontier.insert(_prod)

    solved = False

    while len(frontier):

        candidate = frontier.pop_min()

        #print
        #print IntegerBase2.from_int(target)
        #print candidate
        #from time import sleep
        #sleep(1)

        children = candidate.generate_children()
        for child in children:
            if child.as_int > target.as_int:
                continue
            elif child.as_int == target.as_int:
                print 'Solution!', child
                solved = True
                break
            else:
                frontier.insert(child)
                num_states += 1

        if solved:
            break

    end_time = time()
    print 'States checked:', num_states
    print 'Time taken: {:.2f}s'.format(end_time - start_time)
Beispiel #14
0
def factor1(target):
    start_time = time()
    num_states = 1

    if not isinstance(target, IntegerBaseFixed):
        target = IntegerBaseFixed(target)

    key_func = partial(product_to_error, target=target)
    frontier = BinarySearchTree(key_func)

    for i, j in itertools.combinations_with_replacement(xrange(BASE), 2):
        frontier.insert(ProductFixed(i, j))

    solved = False
    while len(frontier):

        candidate = frontier.pop_min()

        #print
        #print IntegerBaseFixed.from_int(target)
        #print candidate
        #from time import sleep
        #sleep(1)

        if candidate.as_int() == target:
            print 'Solution!', candidate
            break

        children = candidate.generate_children()
        children = filter_digit_length(children, target)
        children = filter_correct_digits(children, target)

        for child in children:
            frontier.insert(child)
        num_states += len(children)

        if not num_states % 10000:
            print 'Checked:', num_states

    end_time = time()
    print 'States checked:', num_states
    print 'Time taken: {:.2f}s'.format(end_time - start_time)
 def test_traverse_in_order(self):
     """
     test the following binary search tree
           4
          / \
         /   \
        2     6
       / \   / \
      1   3  5  7
     """
     bst = BinarySearchTree()
     node_4 = bst.insert(4)
     node_2 = bst.insert(2)
     node_1 = bst.insert(1)
     node_3 = bst.insert(3)
     node_6 = bst.insert(6)
     node_5 = bst.insert(5)
     node_7 = bst.insert(7)
     ordered_tree = bst.traverse_in_order()
     expected = [node_1, node_2, node_3, node_4, node_5, node_6, node_7]
     self.assertTrue(all(a == b for a, b in zip(ordered_tree, expected)))
#encoding=utf8

from binary_search_tree import BinarySearchTree

if __name__ == '__main__':
	bst = BinarySearchTree()
	bst.insert_node(3,3)
	bst.insert_node(1,1)
	bst.insert_node(5,5)
	bst.insert_node(4,4)
	bst.insert_node(2,2)
	bst.print_tree()
	
class BinarySearchTreeTests(unittest.TestCase):
    def setUp(self):
        self.bst = BinarySearchTree(5)

    def test_depth_first_for_each_executes_callback(self):
        arr = []

        def cb(x):
            arr.append(x)

        self.bst.insert(2)
        self.bst.insert(3)
        self.bst.insert(7)
        self.bst.insert(9)
        self.bst.depth_first_for_each(cb)

        self.assertEqual(arr, [5, 2, 3, 7, 9])

    def test_breadth_first_for_each_executes_callback(self):
        arr = []

        def cb(x):
            arr.append(x)

        self.bst.insert(3)
        self.bst.insert(4)
        self.bst.insert(10)
        self.bst.insert(9)
        self.bst.insert(11)
        self.bst.breadth_first_for_each(cb)

        self.assertEqual(arr, [5, 3, 10, 4, 9, 11])
Beispiel #18
0
from binary_search_tree import BinarySearchTree

# Set up tree
tree = BinarySearchTree(4)

# Insert tree elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)

# Test search
print(tree.search(4))
print(tree.search(6))
Beispiel #19
0
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

# duplicates = []
# for name_1 in names_1:
#     for name_2 in names_2:
#         if name_1 == name_2:
#             duplicates.append(name_1)

# using BST to improve speed

duplicates = []
bst = BinarySearchTree("names")

for name_1 in names_1:
    bst.insert(name_1)
for name_2 in names_2:
    if bst.contains(name_2):
        duplicates.append(name_2)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish with no restrictions on techniques or data
# structures?
    bt.add(6)
    bt.add(9)
    bt.add(15)
    bt.add(12)
    bt.add(11)
    bt.add(14)
    bt.add(17)
    bt.add(16)
    bt.add(19)


# small tree

if False:

    bt = BinarySearchTree()
    bt.add('a')
    bt.add('d')
    bt.add('e')
    bt.add('f')
    bt.add('b')
    bt.add('c')

    bt.show_all()
    bt.show_all_visual()

    for e in ['a', 'e', 'j']:
        check_for(bt, e)

    print
Beispiel #21
0
 def test_insert(self):
     tree = BinarySearchTree()
     array = [5, 1, 7, 4, 3, 6, 9, 10, 19, 15]
     for item in array:
         tree.insert(item)
     self.assertEqual(tree.root.right.left.data, 6)
Beispiel #22
0
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []
"""for name_1 in names_1:
    for name_2 in names_2:
        if name_1 == name_2:
            duplicates.append(name_1)"""

search = BinarySearchTree('names')

for names in names_1:
    search.insert(names)
for name in names_2:
    if search.contains(name):
        duplicates.append(name)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish with no restrictions on techniques or data
# structures?
Beispiel #23
0
 def setUp(self):
     self.bst = BinarySearchTree(5)
Beispiel #24
0
class BinarySearchTreeTests(unittest.TestCase):
    def setUp(self):
        self.bst = BinarySearchTree(5)

    def test_insert(self):
        self.bst.insert(2)
        self.bst.insert(3)
        self.bst.insert(7)
        self.bst.insert(6)
        self.assertEqual(self.bst.left.right.value, 3)
        self.assertEqual(self.bst.right.left.value, 6)

    def test_handle_dupe_insert(self):
        self.bst2 = BinarySearchTree(1)
        self.bst2.insert(1)
        self.assertEqual(self.bst2.right.value, 1)

    def test_contains(self):
        self.bst.insert(2)
        self.bst.insert(3)
        self.bst.insert(7)
        self.assertTrue(self.bst.contains(7))
        self.assertFalse(self.bst.contains(8))

    def test_get_max(self):
        self.assertEqual(self.bst.get_max(), 5)
        self.bst.insert(30)
        self.assertEqual(self.bst.get_max(), 30)
        self.bst.insert(300)
        self.bst.insert(3)
        self.assertEqual(self.bst.get_max(), 300)

    def test_for_each(self):
        arr = []

        def cb(x):
            return arr.append(x)

        v1 = random.randint(1, 101)
        v2 = random.randint(1, 101)
        v3 = random.randint(1, 101)
        v4 = random.randint(1, 101)
        v5 = random.randint(1, 101)

        self.bst.insert(v1)
        self.bst.insert(v2)
        self.bst.insert(v3)
        self.bst.insert(v4)
        self.bst.insert(v5)

        self.bst.for_each(cb)

        self.assertTrue(5 in arr)
        self.assertTrue(v1 in arr)
        self.assertTrue(v2 in arr)
        self.assertTrue(v3 in arr)
        self.assertTrue(v4 in arr)
        self.assertTrue(v5 in arr)

    def test_print_traversals(self):
        # WARNING:  Tests are for Print()
        # Debug calls to Print() in functions will cause failure

        stdout_ = sys.stdout  # Keep previous value
        sys.stdout = io.StringIO()

        self.bst = BinarySearchTree(1)
        self.bst.insert(8)
        self.bst.insert(5)
        self.bst.insert(7)
        self.bst.insert(6)
        self.bst.insert(3)
        self.bst.insert(4)
        self.bst.insert(2)

        # self.bst.in_order_print(self.bst)
        # output = sys.stdout.getvalue()
        # self.assertEqual(output, "1\n2\n3\n4\n5\n6\n7\n8\n")

        sys.stdout = io.StringIO()
        self.bst.bft_print(self.bst)
        output = sys.stdout.getvalue()
        self.assertTrue(output == "1\n8\n5\n3\n7\n2\n4\n6\n"
                        or output == "1\n8\n5\n7\n3\n6\n4\n2\n")

        sys.stdout = io.StringIO()
        self.bst.dft_print(self.bst)
        output = sys.stdout.getvalue()
        self.assertTrue(output == "1\n8\n5\n7\n6\n3\n4\n2\n"
                        or output == "1\n8\n5\n3\n2\n4\n7\n6\n")

        # # sys.stdout = io.StringIO()
        # self.bst.pre_order_dft(self.bst)
        # output = sys.stdout.getvalue()
        # self.assertEqual(output, "1\n8\n5\n3\n2\n4\n7\n6\n")

        # sys.stdout = io.StringIO()
        # self.bst.post_order_dft(self.bst)
        # output = sys.stdout.getvalue()
        # self.assertEqual(output, "2\n4\n3\n6\n7\n5\n8\n1\n")

        sys.stdout = stdout_  # Restore stdout
class TestBinarySearchTree(unittest.TestCase):

    def setUp(self):
        self.tree = BinarySearchTree()

    def test_basic_initialization_and_repr(self):
        self.assertEqual(repr(self.tree), '')

    def test_insert(self):
        self.tree.insert('C')
        self.assertEqual(repr(self.tree), 'C ')
        self.tree.insert('D')
        self.assertEqual(repr(self.tree), 'C D ')
        self.tree.insert('A')
        self.assertEqual(repr(self.tree), 'A C D ')
        self.tree.insert('B')
        self.assertEqual(repr(self.tree), 'A B C D ')
        self.tree.insert('F')
        self.assertEqual(repr(self.tree), 'A B C D F ')
        self.tree.insert('E')
        self.assertEqual(repr(self.tree), 'A B C D E F ')

    def test_iterator(self):
        letters = []
        for node in self.tree:
            letters.append(node)
        self.assertEqual(letters, [])
        self.tree.insert('C')
        self.tree.insert('D')
        self.tree.insert('A')
        self.tree.insert('B')
        self.tree.insert('F')
        self.tree.insert('E')
        for node in self.tree:
            letters.append(node)
        self.assertEqual(letters, ['A', 'B', 'C', 'D', 'E', 'F'])

    def test_height(self):
        self.assertEqual(self.tree.height(self.tree.root), -1)
        self.tree.insert('C')
        self.assertEqual(self.tree.height(self.tree.root), 0)
        self.tree.insert('D')
        self.assertEqual(self.tree.height(self.tree.root), 1)
        self.tree.insert('A')
        self.assertEqual(self.tree.height(self.tree.root), 1)
        self.tree.insert('L')
        self.assertEqual(self.tree.height(self.tree.root), 2)
        self.tree.insert('X')
        self.assertEqual(self.tree.height(self.tree.root), 3)
        self.tree.insert('B')
        self.assertEqual(self.tree.height(self.tree.root), 3)

    def test_length(self):
        self.assertEqual(self.tree.length(), 0)
        self.assertEqual(len(self.tree), 0)
        self.tree.insert('C')
        self.assertEqual(self.tree.length(), 1)
        self.assertEqual(len(self.tree), 1)
        self.tree.insert('D')
        self.assertEqual(self.tree.length(), 2)
        self.assertEqual(len(self.tree), 2)
        self.tree.insert('A')
        self.assertEqual(self.tree.length(), 3)
        self.assertEqual(len(self.tree), 3)
        self.tree.insert('B')
        self.assertEqual(self.tree.length(), 4)
        self.assertEqual(len(self.tree), 4)
        self.tree.remove('D')
        self.assertEqual(self.tree.length(), 3)
        self.assertEqual(len(self.tree), 3)
        self.tree.remove('B')
        self.assertEqual(self.tree.length(), 2)
        self.assertEqual(len(self.tree), 2)
        self.tree.remove('A')
        self.assertEqual(self.tree.length(), 1)
        self.assertEqual(len(self.tree), 1)
        self.tree.remove('C')
        self.assertEqual(self.tree.length(), 0)
        self.assertEqual(len(self.tree), 0)

    def test_contains(self):
        self.tree.insert('C')
        self.tree.insert('D')
        self.tree.insert('A')
        self.assertTrue('A' in self.tree)
        self.assertTrue('C' in self.tree)
        self.assertTrue('D' in self.tree)
        self.assertFalse('B' in self.tree)
        self.assertFalse(None in self.tree)

    def test_search(self):
        self.tree.insert('C')
        self.tree.insert('D')
        self.tree.insert('A')
        self.tree.insert('B')
        self.tree.insert('F')
        self.tree.insert('E')
        self.assertEqual(self.tree.search('A').data, 'A')
        self.assertEqual(self.tree.search('B').data, 'B')
        self.assertEqual(self.tree.search('C').data, 'C')
        self.assertEqual(self.tree.search('D').data, 'D')
        self.assertEqual(self.tree.search('E').data, 'E')
        self.assertEqual(self.tree.search('F').data, 'F')
        self.assertEqual(self.tree.search('G'), None)

    def test_remove(self):
        self.tree.insert('C')
        self.tree.insert('D')
        self.tree.insert('A')
        self.tree.insert('B')
        self.tree.insert('F')
        self.tree.insert('E')
        self.assertEqual(repr(self.tree), 'A B C D E F ')
        self.tree.remove('E')
        self.assertEqual(repr(self.tree), 'A B C D F ')
        self.tree.remove('B')
        self.assertEqual(repr(self.tree), 'A C D F ')
        self.tree.remove('A')
        self.assertEqual(repr(self.tree), 'C D F ')
        self.tree.remove('C')
        self.assertEqual(repr(self.tree), 'D F ')
        self.tree.remove('D')
        self.assertEqual(repr(self.tree), 'F ')
        self.tree.remove('F')
        self.assertEqual(repr(self.tree), '')

    def test_in_order(self):
        self.tree.insert('F')
        self.tree.insert('G')
        self.tree.insert('B')
        self.tree.insert('A')
        self.tree.insert('D')
        self.tree.insert('I')
        self.tree.insert('H')
        self.tree.insert('E')
        self.tree.insert('C')
        self.assertEqual(self.tree.in_order(self.tree.root), 'A B C D E F G H I ')

    def test_pre_order(self):
        self.tree.insert('F')
        self.tree.insert('G')
        self.tree.insert('B')
        self.tree.insert('A')
        self.tree.insert('D')
        self.tree.insert('I')
        self.tree.insert('H')
        self.tree.insert('E')
        self.tree.insert('C')
        self.assertEqual(self.tree.pre_order(self.tree.root), 'F B A D C E G I H ')

    def test_post_order(self):
        self.tree.insert('F')
        self.tree.insert('G')
        self.tree.insert('B')
        self.tree.insert('A')
        self.tree.insert('D')
        self.tree.insert('I')
        self.tree.insert('H')
        self.tree.insert('E')
        self.tree.insert('C')
        self.assertEqual(self.tree.post_order(self.tree.root), 'A C E D B H I G F ')
Beispiel #26
0
 def __init__(self, inner_tree=None):
     self._innertree = BinarySearchTree() if not inner_tree else inner_tree
 def setUp(self):
     self.tree = BinarySearchTree()
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []  # Return the list of duplicates in this data structure

# Replace the nested for loops below with your improvements
# for name_1 in names_1:
#     for name_2 in names_2:
#         if name_1 == name_2:
#             duplicates.append(name_1)

# Create and call a new node list for a binary search
bst = BinarySearchTree('names')

# Loop through all the names in the first list
for name in names_1:
    # Insert names into our binary search tree
    bst.insert(name)

# Loop through all the names in our second list
for name in names_2:
    # If our first list contains any names from the second list
    if bst.contains(name):
        # Add those names to our duplicates list
        duplicates.append(name)

end_time = time.time()
print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
Beispiel #29
0
from binary_search_tree import BinarySearchTree

test = BinarySearchTree(100)

for i in range(51, 153, 2):
    test.insert(i)

testarr1 = []

testarr2 = []

testarr3 = []


def cb1(x): return testarr1.append(x)


def cb2(x): return testarr2.append(x)


def cb3(x): return testarr3.append(x)


test.for_each_before(cb1)
test.for_each_middle(cb2)
test.for_each_after(cb3)
print(f"For Each Before\n", testarr1)
print(f"For Each Middle\n", testarr2)
print(f"For Each After\n", testarr3)
import time
from binary_search_tree import BinarySearchTree

start_time = time.time()

f = open('names_1.txt', 'r')
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

names_bst = BinarySearchTree(names_1[0])
duplicates = []

# do two for loops

# second loop will append identical names to the duplicates array
for name_1 in names_1[1:]:
    # use the insert method from bst to add name_1
    names_bst.insert(name_1)

for name_2 in names_2:
    # if name_2 == to a name_1 insert the name with the bst method append!
    if names_bst.contains(name_2):
        duplicates.append(name_2)
# for name_1 in names_1:
#     for name_2 in names_2:
#         if name_1 == name_2:
#             duplicates.append(name_1)
Beispiel #31
0
class BinarySearchTreeTests(unittest.TestCase):
    def setUp(self):
        self.bst = BinarySearchTree(5)

    def test_breadth_first_traversal_1(self):
        arr = []
        cb = lambda x: arr.append(x)

        self.bst.breadth_first_for_each(cb)

        # self.assertEqual(arr, [5])

    def test_breadth_first_traversal_2(self):
        arr = []
        cb = lambda x: arr.append(x)

        self.bst.insert(3)
        self.bst.insert(4)
        self.bst.insert(10)
        self.bst.insert(9)
        self.bst.insert(11)
        self.bst.breadth_first_for_each(cb)

        self.assertEqual(arr, [5, 3, 10, 4, 9, 11])
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []  # Return the list of duplicates in this data structure

# Replace the nested for loops below with your improvements
##### BELOW CODE RUNS IN O(n^2) ##########################
# for name_1 in names_1:
#    for name_2 in names_2:
#        if name_1 == name_2:
#            duplicates.append(name_1)

# Put names_1 into tree
names_1_bst = BinarySearchTree('M')  #initialize tree
for name_1 in names_1:
    names_1_bst.insert(name_1)

# Search for each name in tree
for name_2 in names_2:
    if names_1_bst.contains(name_2):
        duplicates.append(name_2)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish?  Thare are no restrictions on techniques or data
Beispiel #33
0
import time
from binary_search_tree import BinarySearchTree

start_time = time.time()

f = open('names_1.txt', 'r')
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []  # Return the list of duplicates in this data structure
tree = BinarySearchTree("")

# Add all names in names_1 to BST
for name_1 in names_1:
    tree.insert(name_1)

# Search in tree for names in names_2 and add to duplicates if found
for name_2 in names_2:
    if tree.contains(name_2):
        duplicates.append(name_2)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
Beispiel #34
0
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()
''' 
Orignal code needed to be replaced


duplicates = []
for name_1 in names_1:
    for name_2 in names_2:
        if name_1 == name_2:
            duplicates.append(name_1)
'''

#New code start
duplicates = []
names_1_tree = BinarySearchTree(names_1[0])
for i in range(1, len(names_1)):
    names_1_tree.insert(names_1[i])

for i in names_2:
    if names_1_tree.contains(i):
        duplicates.append(i)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")
            size = len(q)
            level = []
            for i in range(0, size):
                cur = q.popleft()
                level.append(cur.val)
                if cur.left is not None:
                    q.append(cur.left)
                if cur.right is not None:
                    q.append(cur.right)
            result.append(level)

        return result


if __name__ == "__main__":
    bt = BinarySearchTree()
    s = Solution()

    nums = [2, 1, 4, 6, 2, 3, 6]
    root = bt.build_binary_search_tree(nums)
    print s.levelOrder(root)

    nums = [2, 1, 3]
    root = bt.build_binary_search_tree(nums)
    print s.levelOrder(root)

    nums = [2, 1, 3, 4, 5]
    root = bt.build_binary_search_tree(nums)
    print s.levelOrder(root)

    nums = [3, 2, 1, 4, 5]
def insert_tree(data):
    root = Node(data[0], 'root')
    bst = BinarySearchTree(root)
    for i in data[1:]:
        bst.insert(i)
    return bst
	def __init__(self, size=100, capacity=120):
		self.size = size
		self.capacity = capacity
		self.current_size = 0
		self.stats_init()
		self.tree = BinarySearchTree()
 def test_smaller_data_at_left_node(self):
     expected = TreeNode('4', TreeNode('2', None, None), None)
     self.assertTreeEqual(BinarySearchTree(['4', '2']).data(), expected)
 def test_same_number_at_left_node(self):
     expected = TreeNode('4', TreeNode('4', None, None), None)
     self.assertTreeEqual(BinarySearchTree(['4', '4']).data(), expected)
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []  # Return the list of duplicates in this data structure

# Replace the nested for loops below with your improvements
# for name_1 in names_1:
#     for name_2 in names_2:
#         if name_1 == name_2:
#             duplicates.append(name_1)

# The runtime before was 0(n^2) due to the loop nested in another loop and now it is O(n log n)

tree = BinarySearchTree('')

tree.insert_list(names_1)

tree.check_for_duplicates(names_2, duplicates)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish?  Thare are no restrictions on techniques or data
# structures, but you may not import any additional libraries that you did not write yourself.
 def test_greater_number_at_right_node(self):
     expected = TreeNode('4', None, TreeNode('5', None, None))
     self.assertTreeEqual(BinarySearchTree(['4', '5']).data(), expected)
Beispiel #42
0
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []  # Return the list of duplicates in this data structure

# Replace the nested for loops below with your improvements
for name_1 in names_1:
    for name_2 in names_2:
        if name_1 == name_2:
            duplicates.append(name_1)
'''Using binary search tree and the insert+append methods for stacks '''
from binary_search_tree import BinarySearchTree
# Inserting the values into the tree
bst = BinarySearchTree(names_1[0])
for name in names_1:
    bst.insert(name)
duplicates = []
# using pythons .contains and getting any names that are in the binary search tree and appending them to
# the list of duplicates
for name in names_2:
    if bst.contains(name):
        duplicates.append(name)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
 def test_can_sort_single_number(self):
     self.assertEqual(BinarySearchTree(['2']).sorted_data(), ['2'])
Beispiel #44
0
from binary_search_tree import BinarySearchTree

start_time = time.time()

f = open('names_1.txt', 'r')
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []  # Return the list of duplicates in this data structure

binary_tree = BinarySearchTree('names')

for names in names_1:
    binary_tree.insert(names)

for name in names_2:
    if binary_tree.contains(name):
        duplicates.append(name)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# INITIAL RUNTIME: 6.331447124481201 seconds

# OPTIMIZED RUNTIME: 0.10910296440124512 seconds
 def test_can_sort_if_second_number_is_same_as_first(self):
     self.assertEqual(
         BinarySearchTree(['2', '2']).sorted_data(), ['2', '2'])
class BinarySearchTreeTests(unittest.TestCase):
    def setUp(self):
        self.bst = BinarySearchTree(5)

    def test_insert(self):
        self.bst.insert(2)
        self.bst.insert(3)
        self.bst.insert(7)
        self.bst.insert(6)
        self.assertEqual(self.bst.left.right.value, 3)
        self.assertEqual(self.bst.right.left.value, 6)

    def test_contains(self):
        self.bst.insert(2)
        self.bst.insert(3)
        self.bst.insert(7)
        self.assertTrue(self.bst.contains(7))
        self.assertFalse(self.bst.contains(8))

    def test_get_max(self):
        self.assertEqual(self.bst.get_max(), 5)
        self.bst.insert(30)
        self.assertEqual(self.bst.get_max(), 30)
        self.bst.insert(300)
        self.bst.insert(3)
        self.assertEqual(self.bst.get_max(), 300)

    def test_for_each(self):
        arr = []
        cb = lambda x: arr.append(x)

        v1 = random.randint(1, 101)
        v2 = random.randint(1, 101)
        v3 = random.randint(1, 101)
        v4 = random.randint(1, 101)
        v5 = random.randint(1, 101)

        self.bst.for_each(cb)

        self.assertTrue(5 in arr)
        self.assertTrue(v1 in arr)
        self.assertTrue(v2 in arr)
        self.assertTrue(v3 in arr)
        self.assertTrue(v4 in arr)
        self.assertTrue(v5 in arr)
 def test_can_sort_if_second_number_is_greater_than_first(self):
     self.assertEqual(
         BinarySearchTree(['2', '3']).sorted_data(), ['2', '3'])
Beispiel #48
0
 def test_handle_dupe_insert(self):
     self.bst2 = BinarySearchTree(1)
     self.bst2.insert(1)
     self.assertEqual(self.bst2.right.value, 1)
 def test_can_sort_complex_tree(self):
     self.assertEqual(
         BinarySearchTree(['2', '1', '3', '6', '7', '5']).sorted_data(),
         ['1', '2', '3', '5', '6', '7'])
Beispiel #50
0
def main():
    args = parse_argument()
    log.debug(args)

    if args.max_num == 3:
        from test_binary_search_tree import three_data as data
    elif args.max_num == 5:
        from test_binary_search_tree import five_data as data
    elif args.max_num == 8:
        from test_binary_search_tree import eight_data as data
    elif args.max_num == 12:
        from test_binary_search_tree import twelve_data as data
    elif args.max_num == 17:
        from test_binary_search_tree import seventeen_data as data
    else:
        data = list(random.sample(range(args.max_num), args.max_num))

    log.info(data)
    first = data.pop(0)
    root = Node(first, 'root')

    bst = BinarySearchTree(root)
    for i in data:
        bst.insert(i)

    print('=== initial tree structure ===')
    bst.show()

    if args.target_key is not None:
        set_parent(bst.root)
        key = args.target_key
        node = bst.search(key)
        print('search:', node)

        if node.attr == 'left' or node.attr == 'root':
            print('=== target %d, rotating left ===' % key)
            rotate_left(node, bst)
            bst.show()

            print('=== target %d, rotating right ===' % node.parent.key)
            rotate_right(node.parent, bst)
            bst.show()
        elif node.attr == 'right':
            print('=== target %d, rotating right ===' % key)
            rotate_right(node, bst)
            bst.show()

            print('=== target %d, rotating left ===' % node.parent.key)
            rotate_left(node.parent, bst)
            bst.show()
 def test_data_is_retained(self):
     expected = TreeNode('4', None, None)
     self.assertTreeEqual(BinarySearchTree(['4']).data(), expected)
  bt.add(7)
  bt.add(6)
  bt.add(9)
  bt.add(15)
  bt.add(12)
  bt.add(11)
  bt.add(14)
  bt.add(17)
  bt.add(16)
  bt.add(19)

# small tree

if False:

  bt = BinarySearchTree()
  bt.add('a')
  bt.add('d')
  bt.add('e')
  bt.add('f')
  bt.add('b')
  bt.add('c')

  bt.show_all()
  bt.show_all_visual()

  for e in ['a','e','j']:
    check_for(bt,e)

  print
Beispiel #53
0
class SplayTree:
    def __init__(self, inner_tree=None):
        self._innertree = BinarySearchTree() if not inner_tree else inner_tree

    def __setitem__(self, key, value):
        self._innertree[key] = value
        self.__splay(key)

    def __getitem__(self, key):
        if self._innertree.key != key:
            # upgrade to root
            self.__splay(key)
        # we only bother in getting the value _if_ we splayed with success, otherwise
        # the element doesn't exist
        if self._innertree.key == key:
            return self._innertree[key]

    def __delitem__(self, key):
        self.__splay(key)
        # we do this test for the same reason we do it in __getitem__
        if self._innertree.key == key:
            del self._innertree[key]

    def __splay(self, key):
        subtree = self._innertree._getsubtree(key)
        if subtree:
            while not subtree.parent is None:
                if self.__should_zig(subtree):
                    # parent is root
                    self.__zig(subtree)
                elif self.__should_zigzig(subtree):
                    # both element and parent are on the same subtree
                    self.__zigzig(subtree)
                else:
                    # element is one subtree, parent is in another
                    self.__zigzag(subtree)
            self._innertree = subtree

    def __zig(self, subtree):
        parent = subtree.parent
        gparent = subtree.parent.parent
        if gparent and self.__isleftchild(parent):
            gparent.left = subtree
        elif gparent and self.__isrightchild(parent):
            gparent.right = subtree
        # rotate to the right if node is left child
        if self.__isleftchild(subtree):
            rightside = subtree.right
            subtree.right = parent
            parent.parent = subtree
            parent.left = rightside
            subtree.parent = gparent
        # rotate to the left if node is right child
        elif self.__isrightchild(subtree):
            leftside = subtree.left
            subtree.left = parent
            parent.parent = subtree
            parent.right = leftside
            subtree.parent = gparent

    def __zigzig(self, subtree):
        self.__zig(subtree.parent)
        self.__zig(subtree)

    def __zigzag(self, subtree):
        self.__zig(subtree)
        self.__zig(subtree)

    def __should_zig(self, subtree):
        return subtree.parent.parent is None

    def __should_zigzig(self, subtree):
        return self.__bothleft(subtree, subtree.parent) or self.__bothright(subtree, subtree.parent)

    def __isleftchild(self, subtree):
        return subtree.parent.left == subtree

    def __isrightchild(self, subtree):
        return subtree.parent.right == subtree

    def __bothleft(self, subtree1, subtree2):
        return self.__isleftchild(subtree1) and self.__isleftchild(subtree2)

    def __bothright(self, subtree1, subtree2):
        return self.__isrightchild(subtree1) and self.__isrightchild(subtree2)