Exemplo n.º 1
0
def prep():
    Binary_tree = BinaryTree()
    Binary_tree.root = Node(3)
    Binary_tree.root.right = Node(4)
    Binary_tree.root.left = Node(1)
    Binary_tree.root.right.left = Node(2)
    return Binary_tree
Exemplo n.º 2
0
def test_post_order_traversal():
    for nodes, expected_result in [
        (
            (
                8,
                [(4,
                  [2, 6]),
                 (10,
                  [None, 20])]
            ),
            "2->6->4->20->10->8"
        ),
        (
            (1, ), "1"
        ),

        (
            (1, [2]), "2->1"
        ),

        (
            (1, [None, 2]), "2->1"
        ),
    ]:
        result = []
        def visit(node: Node) -> None:
            result.append(node.val)

        bt = BinaryTree(BinaryTree.build(nodes))
        bt.post_order(visit)

        result = "->".join([str(val) for val in result])
        assert result == expected_result, "{} != {}".format(result, expected_result)
Exemplo n.º 3
0
 def fn3(newickTree, i):
     if newickTree[i[0]] == '(':
         #subTree1 = None
         subTreeList = []
         i[0] += 1
         k = []
         while newickTree[i[0]] != ')':
             if newickTree[i[0]] == ',':
                 i[0] += 1
             subTreeList.append(fn3(newickTree, i))
         i[0] += 1
         def cmp(i, j):
             if i.distance < j.distance:
                 return -1
             if i.distance > j.distance:
                 return 1
             return 0
         if sortNonBinaryNodes:
             subTreeList.sort(cmp)
         subTree1 = subTreeList[0]
         if len(subTreeList) > 1:
             for subTree2 in subTreeList[1:]:
                 subTree1 = BinaryTree(0.0, True, subTree1, subTree2, None)
             subTree1.iD = fn2(newickTree, i)
             subTree1.distance += fn(newickTree, i)
         elif reportUnaryNodes:
             subTree1 = BinaryTree(0.0, True, subTree1, None, None)
             subTree1.iD = fn2(newickTree, i)
             subTree1.distance += fn(newickTree, i)
         else:
             fn2(newickTree, i)
             subTree1.distance += fn(newickTree, i)
         return subTree1
     leafID = fn2(newickTree, i)
     return BinaryTree(fn(newickTree, i), False, None, None, leafID)
Exemplo n.º 4
0
def postorder_example_tree():
    tree = BinaryTree()
    n1 = Node('I')
    n2 = Node('N')
    n3 = Node('S')
    n4 = Node('C')
    n5 = Node('R')
    n6 = Node('E')
    n7 = Node('V')
    n8 = Node('A')
    n9 = Node('5')
    n0 = Node('3')

    n0.left = n6
    n0.right = n9
    n6.left = n1
    n6.right = n5
    n5.left = n2
    n5.right = n4
    n4.right = n3
    n9.left = n8
    n8.right = n7

    tree.root = n0
    return tree
Exemplo n.º 5
0
def test_empty():
    tree = BinaryTree()
    b, v = tree.find_max(tree)
    assert b == False

    b,v = BinaryTree().find_max(None)
    assert b == False
Exemplo n.º 6
0
def test_max_val_same_el():
    tree = BinaryTree(1)
    tree.root.left = Node(-3)
    tree.root.left.left = Node(-3)
    tree.root.left.left.left = Node(-3)
    tree.root.left.left.left.left = Node(-3)
    assert tree.find_maximum_value() == 1
def tree():

    one = Node(1)
    two = Node(2)
    three = Node(3)
    four = Node(4)
    five = Node(5)
    six = Node(6)
    seven = Node(7)
    eight = Node(8)
    nine = Node(9)

    one.left = two
    one.right = three
    three.left = four
    three.right = five
    two.left = six
    six.right = seven
    seven.left = eight
    seven.right = nine

    arbol = BinaryTree()
    arbol.root = one

    return arbol
def tree_intersection(tree1, tree2: BinaryTree) -> list:
    # return an array with all the values in both tree1 and tree2
    # BigO Time==O(2n)  Space==0(1.3n) 30% for hashtable
    # assumption: No Duplicates within Trees

    # return early
    if not isinstance(tree1, BinaryTree) or not isinstance(tree2, BinaryTree):
        raise ValueError('Must pass BinaryTree for parameters.')
    if not tree1.root or not tree2.root:
        return []

    # init local vars
    ht = HashTable()
    retArray = []

    # callbacks for traversal of binary tree
    def _add(node):
        # used for the 1st tree to define a list of values
        ht.add(str(node.value), 1)

    def _add_isdup(node):
        # used for the 2nd tree, if its already there, then
        # its a candidate for return
        try:
            ht.add(str(node.value), 1)
        except ValueError:
            retArray.append(node.value)

    # Traverse through both trees, different callback func
    tree1.traverse(TraverseMethod.IN_ORDER, _add)
    tree2.traverse(TraverseMethod.IN_ORDER, _add_isdup)

    return retArray
def test_Can_successfully_instantiate_a_tree_with_a_single_root_node():
    tree = BinaryTree()
    a = Node("A")
    tree.root = a
    actual = tree.root.value
    expected = "A"
    assert actual == expected
def test_func_match_some(tree):

    tree1 = tree
    tree2 = BinaryTree()
    one = Node(1)
    two = Node(2)
    three = Node(3)
    four = Node(4)
    five = Node(5)
    six = Node(6)
    seven = Node(7)
    eight = Node(8)
    nine = Node(9)

    one.left = two
    one.right = three
    three.left = four
    two.left = six
    six.right = seven
    seven.left = eight
    tree2.root = one

    expected = [6, 8, 7, 2, 1, 4, 3]
    actual = tree_intersection(tree1, tree2)
    assert expected == actual
Exemplo n.º 11
0
def test_breadth_first_bt():
    tree = BinaryTree(4)
    tree.root.left = Node(5)
    tree.root.right = Node(7)
    tree.root.left.left = Node(9)
    tree.root.right.right = Node(3)
    tree.root.right.right.right = Node(8)
    assert tree.print_tree('breadth_first') == '4-5-7-9-3-8-'
Exemplo n.º 12
0
def test_find_max():
    tree = BinaryTree(Node(1))
    tree.root.left = Node(3)
    tree.root.right = Node(8)
    tree.root.left.left = Node(72)
    tree.root.left.right = Node(9)
    tree.root.right.left = Node(13)
    assert tree.find_maximum_binary_tree() == 72
Exemplo n.º 13
0
def test_max_val():
    tree = BinaryTree(2)
    tree.root = Node(-1)
    tree.root.left = Node(4)
    tree.root.left.left = Node(7)
    tree.root.left.left.left = Node(3)
    tree.root.left.left.left.left = Node(8)
    assert tree.find_maximum_value() == 8
Exemplo n.º 14
0
def test_three_node_same_BT_max():
    one = Node(3)
    one.left = Node(3)
    one.right = Node(3)

    tree = BinaryTree(one)
    actual = tree.find_maximum_value(tree.root)
    expected = 3
    assert actual == expected
Exemplo n.º 15
0
def test_three_node_neg_num_max():
    one = Node(-3)
    one.left = Node(-4)
    one.right = Node(-1)

    tree = BinaryTree(one)
    actual = tree.find_maximum_value(tree.root)
    expected = -1
    assert actual == expected
Exemplo n.º 16
0
def test_tree_postorder():
    Binary_tree = BinaryTree()
    Binary_tree.root = Node(6)
    Binary_tree.root.right = Node(5)
    Binary_tree.root.left = Node(-1)
    Binary_tree.root.right.left = Node(7)
    Binary_tree.root.left.left = Node(10)
    Binary_tree.root.right.right = Node(3)
    assert Binary_tree.postOrder() == [10, -1, 7, 3, 5, 6]
Exemplo n.º 17
0
def test_tree_inorder():
    Binary_tree = BinaryTree()
    Binary_tree.root = Node(6)
    Binary_tree.root.right = Node(5)
    Binary_tree.root.left = Node(-1)
    Binary_tree.root.right.left = Node(7)
    Binary_tree.root.left.left = Node(10)
    Binary_tree.root.right.right = Node(3)
    assert Binary_tree.inOrder() == [10, -1, 6, 7, 5, 3]
def minHeightTree (array):
	mid = len(array) // 2

	tree = BinaryTree()

	root = Node(array.pop(mid))
	self.root = root

	for nums in array:
		tree.insert(nums)
Exemplo n.º 19
0
def test_edge_negative_maxiumum():
    tree = BinaryTree()
    Node1 = Node(-7)
    Node2 = Node(-8)
    Node3 = Node(-78)
    Node1.left = Node2
    Node1.right = Node3
    tree.root = Node1
    actual = tree.find_maximum_value()
    expected = -7
    assert actual == expected
Exemplo n.º 20
0
def test_easy_queue_breadth():
    tree = BinaryTree()
    Node1 = Node(8)
    Node2 = Node(9)
    Node3 = Node(10)
    Node1.left = Node2
    Node1.right = Node3
    tree.root = Node1
    actual = tree.breadth_first()
    expected = [8,9,10]
    assert actual == expected
def fizz_buzz_tree(tree: BinaryTree) -> BinaryTree:
    # traverse tree, value = value%3==0 ? 'Fizz, value = value%5==0 ? 'Buzz' (set value to 'FizzBuzz' if both conditions met)

    # Base Case
    if tree is None or tree.root is None:
        return tree

    # Great Helper func, that I built into the class to traverse and do something on each node
    tree.traverse(TraverseMethod.IN_ORDER, fizz_buzz_valueswitch)

    return tree
Exemplo n.º 22
0
def test_happy_maximum():
    tree = BinaryTree()
    Node1 = Node(7)
    Node2 = Node(8)
    Node3 = Node(788)
    Node1.left = Node2
    Node1.right = Node3
    tree.root = Node1
    actual = tree.find_maximum_value()
    expected = 788
    assert actual == expected
Exemplo n.º 23
0
 def __init__(self,
              classification_method=("svm", None),
              point_generation_method=1):
     """
     Creates SlantingTree with provided classifier.
     Raises a ValueError exception if provided parameters are incorrect.
     :param classification_method: tuple consisting of string containing name of classification algorithm
     and its parameters (None for default ones)
     """
     BinaryTree.__init__(self)
     self.classifier = classifiers.classifier_object(classification_method)
     self._point_generation_method = point_generation_method
Exemplo n.º 24
0
def test_insert_method_for_BT():
    bt = BinaryTree(BinaryTree.build(SIMPLE_TREE))
    for use_case, *expected_result in [
            (1, True, True, """
-- 8
|  |-- 4
|  |  |-- 2
|  |  |  |-- 1
|  |  |-- 6
|  |-- 10
|  |  |-- 20"""),

            (0, True, True, """
-- 8
|  |-- 4
|  |  |-- 2
|  |  |  |-- 1
|  |  |  |-- 0
|  |  |-- 6
|  |-- 10
|  |  |-- 20"""),

            (3, True, True, """
-- 8
|  |-- 4
|  |  |-- 2
|  |  |  |-- 1
|  |  |  |  |-- 3
|  |  |  |-- 0
|  |  |-- 6
|  |-- 10
|  |  |-- 20"""),
            (8, False, True, """
-- 8
|  |-- 4
|  |  |-- 2
|  |  |  |-- 1
|  |  |  |  |-- 3
|  |  |  |-- 0
|  |  |-- 6
|  |-- 10
|  |  |-- 20"""),
    ]:
        insert_result, find_result, tree_repr = expected_result

        result = bt.insert(use_case)
        assert result == insert_result, "{} != {}".format(result, insert_result)

        result = bt.find(use_case)
        assert result == find_result, "{} != {}".format(result, find_result)

        assert str(bt) == tree_repr, "{} != {}".format(str(bt), tree_repr)
def test_Can_successfully_add_a_left_child_and_right_child_to_a_single_root_node(
):
    pass
    a = Node("A")
    b = Node("B")
    c = Node("C")
    tree = BinaryTree()
    tree.root = a
    a.left = b
    a.right = c
    actual = a.left.value, a.right.value
    expected = "B", "C"
    assert actual == expected
Exemplo n.º 26
0
 def __init__(self,
              clustering_method=("spectral", None),
              classification_method=("svm", None)):
     """
     Creates BalancedTree using provided clustering and classification methods.
     Raises a ValueError exception if provided parameters are incorrect.
     :param clustering_method: tuple consisting of string containing name of clustering algorithm
     and its parameters (None for default ones)
     :param classification_method: tuple consisting of string containing name of classification algorithm
     and its parameters (None for default ones)
     """
     BinaryTree.__init__(self)
     self.clustering = classifiers.clustering_object(clustering_method)
     self.classifier = classifiers.classifier_object(classification_method)
Exemplo n.º 27
0
def tree():
    ten = Node(10)

    ten.left = Node(3)
    ten.right = Node(5)
    ten.left.left = Node(6)
    ten.left.right = Node(9)
    ten.right.right = Node(10)
    ten.right.left = Node(15)

    tree = BinaryTree()
    tree.root = ten

    return tree
Exemplo n.º 28
0
class DBDB(object):
    """
    implement the python dictionary API using concrete BinaryTree implementation
    """
    def __init__(self, f):
        self._storage = PhysicalObject(f)
        # Data stores tend to use more complex types of search trees such as
        # B-trees, B+ trees, and others to improve the performance.
        self._tree = BinaryTree(self._storage)

    def _assert_not_closed(self):
        if self._storage.closed:
            raise ValueError('Database closed!')

    def commit(self):
        self._assert_not_closed()
        self._tree.commit()

    def close(self):
        self._storage.close()

    def __getitem__(self, key):
        self._assert_not_closed()
        return self._tree.get(key)

    def __setitem__(self, key, value):
        self._assert_not_closed()
        return self._tree.set(key, value)

    def __delitem__(self, key):
        self._assert_not_closed()
        return self._tree.delete(key)

    def __contains__(self, key):
        try:
            self[key]
        except KeyError:
            return False
        else:
            return True

    def __len__(self):
        return len(self._tree)

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        if not self._storage.closed:
            self.close()
def test_Can_successfully_return_a_collection_from_a_postorder_traversal():
    a = Node("A")
    b = Node("B")
    c = Node("C")
    d = Node("D")
    e = Node("E")
    tree = BinaryTree()
    tree.root = a
    a.left = b
    a.right = c
    a.left.left = d
    a.left.right = e
    actual = tree.post_order()
    expected = ["D", "E", "B", "C", "A"]
    assert actual == expected
def test_Can_successfully_return_a_collection_from_an_inorder_traversal():
    a = Node("A")  # this assigns value to the node
    b = Node("B")
    c = Node("C")
    d = Node("D")
    e = Node("E")
    tree = BinaryTree()  # this makes the binary tree
    tree.root = a
    a.left = b
    a.right = c
    a.left.left = d
    a.left.right = e
    actual = tree.in_order()
    expected = ["D", "B", "E", "A", "C"]
    assert actual == expected
Exemplo n.º 31
0
def test_emoty_tree():
    """
    Can successfully instantiate an empty tree
    """

    tree = BinaryTree()
    assert tree.root is None
Exemplo n.º 32
0
 def binary_tree(self):
     binary_tree = BinaryTree(1)
     binary_tree.root.left = Node(2)
     binary_tree.root.right = Node(3)
     binary_tree.root.left.left = Node(4)
     binary_tree.root.left.right = Node(5)
     return binary_tree
def buildParseTree(exp):
    exp_lst = exp.split()
    root_node = BinaryTree(" ")
    current_node = root_node
    parent_stack = Stack()
    parent_stack.push(root_node)

    for e in exp_lst:
        if e in ['(']:
            current_node.insertLeft(' ')
            parent_stack.push(current_node)
            current_node = current_node.getLeftChild()
        elif e in ['+', '-', '*', '/']:
            current_node.setRootVal(e)
            current_node.insertRight(' ')
            parent_stack.push(current_node)
            current_node = current_node.getRightChild()
        elif e in [')']:
            current_node = parent_stack.pop()

        elif e not in ['+', '-', '*', '/', '(', ')']:
            try:
                current_node.setRootVal(int(e))
                current_node = parent_stack.pop()
            except ValueError:
                raise ValueError("token '{}' is not a valid number".format(e))

    return current_node
Exemplo n.º 34
0
 def keyPressEvent(self, ev):
     ch = ev.text()
     if ch == 'j':
         self.tree = self.nextTree()
     elif ch == 'k':
         self.tree = self.prevTree()
     elif ch == 'h':
         self.layout = self.prevLayout()
     elif ch == 'l':
         self.layout = self.nextLayout()
     elif ch == 'r':
         trees[self.treeIndex] = BinaryTree.random()
         self.tree = self.curTree()
     else:
         super(Widget, self).keyPressEvent(ev)
     self.init()
Exemplo n.º 35
0
 def __init__(self, f):
     self._storage = PhysicalObject(f)
     # Data stores tend to use more complex types of search trees such as
     # B-trees, B+ trees, and others to improve the performance.
     self._tree = BinaryTree(self._storage)
Exemplo n.º 36
0
        parent = node.parent
        if not parent: return None
    return parent

# 4.7

def common_ancestor(node,p,q):
    if not node: return (None,None,None)
    left = common_ancestor(node.left,p,q)
    right = common_ancestor(node.right,p,q)
    new_p = left[0] or right[0] or (node if node == p else None)
    new_q = left[1] or right[1] or (node if node == q else None)
    result = left[2] or right[2]
    return (new_p, new_q, node if new_p and new_q and not result else result)

t = BinaryTree()
t.insert(5)
t.insert(2)
t.insert(1)
t.insert(3)
t.insert(20)
t.insert(21)
t.insert(22)

common_ancestor(t.root, t.root.left.left, t.root.left.right)[2]
common_ancestor(t.root, t.root.right.right, t.root.right.right.right)[2]
common_ancestor(t.root, t.root.right.right, Node(12))[2]

# 4.8

# not tested except on a single tree selecting subnodes to match
Exemplo n.º 37
0
pca = PCA_sklearn()
pca.fit(predictors, locations, startdate=startdate, enddate=enddate)
# pca.save('pca.nc')
# pca.load('pca.nc')
reduced_predictors = pca.transform(predictors, startdate=startdate, enddate=enddate)

vmin = 0
vmax = 50
mappable = ScalarMappable(cmap="Blues")
mappable.set_array(np.arange(vmin, vmax, 0.1))
mappable.set_clim((vmin, vmax))

id = 20
for pred in reduced_predictors:

    tree = BinaryTree(pred, maxdepth=10)

    fig = plt.fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)
    # 	ax.scatter(np.array(tree.samples)[:,0], np.array(tree.samples)[:,1], s=1, alpha=0.4, color='black')
    values = np.ma.masked_less(predictand_data[:, id], 0.1)
    # 	ax.scatter(np.array(tree.samples)[:,0], np.array(tree.samples)[:,1], c='grey', s=5, alpha=0.3)
    # 	ax.scatter(np.array(tree.samples)[:,0], np.array(tree.samples)[:,1], c=values, s=values, alpha=0.7)
    tree.plot_density(ax, mappable)
    plt.show()

    id += 1

# fig = plt.fig = plt.figure(figsize=(10,10))
# ax = fig.add_subplot(111)
# ax.scatter(reduced_predictors[:,0], reduced_predictors[:,1], s=1, alpha=0.4, color='black')
Exemplo n.º 38
0
if method == 'pca':
	pca = PCA_sklearn()
	pca.fit(predictors, locations, startdate=startdate, enddate=enddate)
	reduced_predictors = pca.transform(predictors, startdate=startdate, enddate=enddate)
	reduced_predictors_subset1 = pca.transform(predictors, startdate=startdate, enddate=enddate, months=[6,7,8])
	reduced_predictors_subset2 = pca.transform(predictors, startdate=startdate, enddate=enddate, months=[12,1,2])



id = 20
for pred in reduced_predictors:

	ranges = zip(np.min(pred, axis=0), np.max(pred, axis=0))

	tree = BinaryTree(pred, ranges=ranges, maxdepth=10)
	tree_subset1 = BinaryTree(reduced_predictors_subset1[id-20], ranges=ranges, maxdepth=10)
	tree_subset2 = BinaryTree(reduced_predictors_subset2[id-20], ranges=ranges, maxdepth=10)
	print "this location is at ", locations[id-20]

	full_volume = tree.volume()
	subset1_volume = tree_subset1.volume()
	subset2_volume = tree_subset2.volume()
	volume_overlap = full_volume - tree_subset1.volume_diff(tree_subset2)

	fig = plt.fig = plt.figure(figsize=(8,8))
	ax = fig.add_subplot(111)

	#vmin = 0
	#vmax = tree.max_leaves()
	#print "max leaves = ", vmax