def tree_from_post_order(postorder):
    """construct a BST from post
    order traversal. We know the
    last elem is root. Left and
    right values are separately
    together. Separate left and
    right elems by determining
    root's place. Recurse"""
    if not postorder:
        return None

    data = postorder.pop()
    node = Tree(data)

    # There was only one node
    if not postorder:
        return node

    loc, _ = BSGE.binary_search_ge(postorder, data)

    # there is no right
    if loc == -1:
        loc = len(postorder)

    node.left = tree_from_post_order(postorder[:loc])
    node.right = tree_from_post_order(postorder[loc:])

    return node
def random_forest(trainX, trainy, trees_num, gr=0):
    i = 0
    forest = []
    while i < trees_num:
        trainset = bootstrap(len(trainX))
        #print(trainset)
        feature_num = trainX.shape[1]
        flags = [1] * feature_num
        K = round(np.log2(feature_num))

        subtree = Tree()

        temp_tree = build_tree(trainX[trainset],
                               trainy[trainset],
                               flags,
                               depth=trainX.shape[1],
                               RF=1,
                               K=K,
                               gr=gr)
        subtree.data = temp_tree.data
        subtree.left = temp_tree.left
        subtree.right = temp_tree.right
        forest.append(subtree)
        print("第几棵树", i)
        i = i + 1
    return forest
Beispiel #3
0
def main():
    t = Tree(3)
    t.left = Tree(1)
    t.right = Tree(5)
    t.right.left = Tree(4)
    t.right.right = Tree(6)

    a = kthSmallestInBST(t, 5)
    print(a)
Beispiel #4
0
 def create_Y_and_root(tree, n):
   all_nodes = tree.nodes()
   for node in all_nodes:
     node.Y = [math.inf] * n
   # create a fake root node so that k.parent doesn't throw an error
   root = Tree(1, "delay", 0.5, "geometric") # The exact values here are irrelevant because root is a fake node
   root.id = -1
   root.left = tree
   root.right = tree
   root.parent = None
   tree.parent = root
Beispiel #5
0
def main():

    t = Tree(1)
    t.left = Tree(2)
    t.right = Tree(2)
    t.left.left = Tree(3)
    t.left.right = Tree(4)
    t.right.left = Tree(4)
    t.right.right = Tree(3)

    print(isTreeSymmetric(t))
Beispiel #6
0
def sen2tree(sen, strategy, flag=False):
    if len(sen) == 1:
        thetree = Tree(sen[0])
        thetree.left = Tree('<end>')
        thetree.right = Tree('<end>')
        thetree.make_index()
        return thetree
    elif len(sen) == 0:
        return Tree('<end>')
    if args.strategy == 'L2R':
        if not flag:
            thetree = Tree('<start>')
            thetree.left = Tree('<end>')
            thetree.right = sen2tree(sen, strategy, True)
            thetree.make_index()
            print_tree(thetree)
            return thetree
        else:
            thetree = Tree(sen[0])
            thetree.left = Tree('<end>')
            thetree.right = sen2tree(sen[1:], strategy, True)
            return thetree
    elif args.strategy == 'R2L':
        if not flag:
            thetree = Tree('<start>')
            thetree.right = Tree('<end>')
            thetree.left = sen2tree(sen, strategy, True)
            thetree.make_index()
            print_tree(thetree)
            return thetree
        else:
            thetree = Tree(sen[-1])
            thetree.right = Tree('<end>')
            thetree.left = sen2tree(sen[0:len(sen) - 1], strategy, True)
            return thetree
    elif args.strategy == 'MID':
        mid = (len(sen) + 1) // 2
        if flag:
            mid = len(sen) // 2
        root = '<start>'
        if flag:
            root = sen[mid]
        thetree = Tree(root)
        if flag:
            thetree.right = sen2tree(sen[mid + 1:], strategy, True)
        else:
            thetree.right = sen2tree(sen[mid:], strategy, True)
        thetree.left = sen2tree(sen[0:mid], strategy, True)
        #thetree.right = sen2tree(sen[mid:], strategy, True)
        if not flag:
            thetree.make_index()
        return thetree
Beispiel #7
0
 def generate_tree(self):
     '''
     obj -> None
     This method generates Huffman tree for given message
     '''
     possibilities = Encoder._sorted_possibilities(self.possibilities)
     while len(possibilities) != 1:
         f_possibility = possibilities[-1]
         s_possibility = possibilities[-2]
         f_possibility = Tree(
             ('', Encoder.calculate_sum_pos(f_possibility, s_possibility)))
         if Encoder._get_possibility(
                 possibilities[-1]) <= Encoder._get_possibility(
                     s_possibility):
             f_possibility.left = possibilities[-1]
             f_possibility.right = s_possibility
         else:
             f_possibility.left = s_possibility
             f_possibility.right = possibilities[-1]
         del possibilities[-1]
         del possibilities[-1]
         possibilities.append(f_possibility)
         possibilities = Encoder._sorted_possibilities(possibilities)
     self.tree = possibilities[-1]
Beispiel #8
0
def construct_tree_from_pre_and_in(pre_order, in_order):
    if not pre_order:
        return None
    root = Tree(pre_order[0])
    index = in_order.index(pre_order[0])

    left_in_order = in_order[:index]
    right_in_order = in_order[index + 1:]
    left_pre_order = pre_order[1:len(left_in_order) + 1]
    right_pre_order = pre_order[len(left_in_order) + 1:]

    root.left = construct_tree_from_pre_and_in(left_pre_order, left_in_order)
    root.right = construct_tree_from_pre_and_in(
        right_pre_order, right_in_order)
    return root
Beispiel #9
0
    def generateInitialPopulation(self):
        """
        Generates the initial population of the evolution
        """

        # iterate over populationSize creating a new tree
        # for each element
        for x in range(self.populationSize):
            new = Tree()
            new.left = Tree()
            new.right = Tree()
            new.value = self.functions[randint(0, 2)]
            self.generatePopulation(new.left, 1)
            self.generatePopulation(new.right, 0)
            self.population.append(new)
Beispiel #10
0
def dict_to_tree(tree_dict):
    if tree_dict is None:
        return None
    
    t = Tree()
    if 'node' in tree_dict:
        node_dict = tree_dict['node']
        node = Node(name=node_dict.get('name', ''), value=node_dict.get('value', None))
        if node.name == 'branches' and isinstance(node.value, list):
            node.value = [dict_to_tree(branch) for branch in node.value]
        t.node = node
            
    if 'left' in tree_dict:
        t.left = dict_to_tree(tree_dict['left'])
    if 'right' in tree_dict:
        t.right = dict_to_tree(tree_dict['right'])
        
    return t
Beispiel #11
0
def preorder_tree(tree):
    stk = []
    result = []

    if not tree:
        return result

    if not isinstance(tree, Tree):
        raise Exception("Not a Tree")
    stk.append(tree)
    while bool(stk):
        curr = stk.pop()
        result.append(curr.value)
        if curr.right is not None:
            stk.append(curr.right)
        if curr.left is not None:
            stk.append(curr.left)

    return result


if __name__ == '__main__':
    root = Tree(2)
    root.left = Tree(3)
    root.right = Tree(4)
    root.left.left = Tree(5)
    root.left.right = Tree(6)
    tests = [root]
    for t in tests:
        print(t, '\'s preorder is: ', preorder_tree(t))
Beispiel #12
0
            total += self.rangeSumBST(root.right, max(root.val, L), R)
            print("---R", total, root.val)
        if root.left:
            total += self.rangeSumBST(root.left, L, min(R, root.val))
            print("---L", total, root.val)
        return total


if __name__ == '__main__':
    from tree import Tree

    this = Tree(5)
    this.left = Tree(3)
    this.left.left = Tree(1)
    this.left.right = Tree(4)
    this.right = Tree(8)
    this.right.right = Tree(10)
    this.right.left = Tree(6)

    this.printTree()

    sol = Solution()

    print(sol.rangeSumBST(this, 4, 7))

    print("test 2")

    this = Tree(15)
    this.left = Tree(9)
    this.left.left = Tree(7)
    this.left.left.left = Tree(5)
    def makeTree(self, Mat, Tag):
        miniumn     = + numpy.inf
        opt_feature = 0
        opt_val     = 0

        Tag = numpy.array(Tag)

        #return the type of data, if there is no different type of data
        if numpy.unique(Tag).size == 1:
            t = Tree()
            t.isLeaf  = True
            t.nodeVal = Tag[0]
            
            for label in self.labels:
                if label != Tag[0]:
                    t.counter[label] = 0.0
                else:
                    t.counter[label] = 1.0
            return t

        minium = + numpy.inf
        for f in range(self.SamplesDem):
            for i in range(len(Tag)):
                v = Mat[f, i]
                p = self.Gini(Mat[f], Tag, v, f)
                p /= self.W[toHashableVal(Mat[:, i])]
                if p < miniumn:
                    miniumn     = p
                    opt_feature = f
                    opt_val     = v

        t = Tree()
        t.nodeVal    = opt_val
        t.selFeature = opt_feature

        if self.currentDepth == self.limitedDepth:
            t.isLeaf = True

            for label in self.labels:
                t.counter[label] = 0

            summer = 0.0
            for i in range(len(Tag)):
                label = Tag[i]
                t.counter[label] += self.W[toHashableVal(Mat[:, i])]
                summer += self.W[toHashableVal(Mat[:, i])]

            for label in numpy.unique(Tag):
                t.counter[label] /= summer
            
            return t

        if miniumn == 1:
            return Tag[0]

        self.currentDepth += 1

        if self.Discrete[opt_feature] == True:
            t.left  = self.makeTree(
                    Mat[:, Mat[opt_feature, :] == opt_val], 
                    Tag[   Mat[opt_feature, :] == opt_val])

            t.right = self.makeTree(
                    Mat[:, Mat[opt_feature, :] != opt_val], 
                    Tag[   Mat[opt_feature, :] != opt_val])
        else:
            t.left  = self.makeTree(
                    Mat[:, Mat[opt_feature, :] <  opt_val], 
                    Tag[   Mat[opt_feature, :] <  opt_val])

            t.right = self.makeTree(
                    Mat[:, Mat[opt_feature, :] >= opt_val], 
                    Tag[   Mat[opt_feature, :] >= opt_val])

        return t
def flat_tree_ite(tree):
    stk = [tree]
    p = tree
    while stk:
        p = stk.pop()
        if p.right:
            stk.append(p.right)
        if p.left:
            stk.append(p.left)
            p.right = None


if __name__ == '__main__':
    root = Tree(2)
    root.left = Tree(3)
    root.right = Tree(4)
    root.left.left = Tree(5)
    root.left.right = Tree(6)
    root.right.right = Tree(8)

    root1 = Tree(2)
    root1.left = Tree(3)
    root1.right = Tree(4)
    root1.left.left = Tree(5)
    root1.left.right = Tree(6)
    root1.right.right = Tree(8)
    root1.right.left = Tree(7)
    tests = [root1]
    for t in tests:
        flat_tree_rec(t)
        p = t
Beispiel #15
0
        print(" %s " % t.val)
        if t.right is not None:
            printTree(t.right)

def f(a, b, node):
    if node.left is not None or node.right is not None:
        if node.val < a and node.right is not None:
            return f(a, b, node.right)
        elif node.val >= b and node.left is not None:
            return f(a, b, node.left)
        else:
            L = f(a, node.val, node.left)
            R = f(node.val, b, node.right)
            return L + R + node.val
    else:
        if node.val >= a and node.val < b:
            return node.val       

if __name__ == "__main__":
    this = Tree(5)
    this.left = Tree(3)
    this.left.left = Tree(1)
    this.left.right = Tree(4)
    this.right = Tree(8)
    this.right.right = Tree(10)
    this.right.left = Tree(6)

    printTree(this)


    print(f(4, 7, this))
Beispiel #16
0
from tree import Tree


def inorder(root):
    current = root
    while current:
        if current.left is None:
            print current.data,
            current = current.right
        else:
            pre = current.left
            while pre.right and pre.right != current:
                pre = pre.right
            if pre.right is None:
                pre.right = current
                current = current.left
            else:
                pre.right = None
                print current.data,
                current = current.right


a = Tree(1)
a.left = Tree(2)
a.right = Tree(3)
a.left.left = Tree(4)
a.right.left = Tree(5)
a.right.right = Tree(6)

inorder(a)
Beispiel #17
0
import unittest

from tree import Tree, sum_nodes, count_nodes, average

root = Tree(5)
root.left = Tree(3)
root.right = Tree(7)
root.left.left = Tree(2)
root.left.right = Tree(5)
root.right.left = Tree(1)
root.right.right = Tree(0)
root.right.right.left = Tree(2)
root.right.right.right = Tree(8)
root.right.right.right.right = Tree(5)


class TestTree(unittest.TestCase):
    def test_should_return_nodes_sum(self):
        self.assertEqual(38, sum_nodes(root))
        self.assertEqual(10, sum_nodes(root.left))
        self.assertEqual(2, sum_nodes(root.left.left))
        self.assertEqual(5, sum_nodes(root.left.right))
        self.assertEqual(23, sum_nodes(root.right))
        self.assertEqual(1, sum_nodes(root.right.left))
        self.assertEqual(15, sum_nodes(root.right.right))
        self.assertEqual(2, sum_nodes(root.right.right.left))
        self.assertEqual(13, sum_nodes(root.right.right.right))
        self.assertEqual(5, sum_nodes(root.right.right.right.right))

    def test_should_count_nodes(self):
        self.assertEqual(10, count_nodes(root))