def optimal_policy(root,r,dt,q,depth):

    # Find optimal action at each time state given a payoffs tree, risk-neutral probabilities and discount factor
    
    #Inputs:
    #root: Payoff value tree
    #r: risk free rate
    #dt: time interval b/w option exercise
    #q: risk neutral probability of asset increasing in price
    #depth: depth of tree
    
    #returns:
    #action_tree: binary tree of optimal actions for non-leaf state nodes
    #expectation_tree:  binary tree of expected optimal value functions at (t+1) for non-leaf state nodes
    
    num_parents=len(root)-root.leaf_count;
    
    list_vals=root.values;
    expected_payoffs=[];
    optimal_action=[];
    discount_factor=np.exp(-r*dt)
    for i in range(num_parents):
        exp_payoff=(q*list_vals[2*i+2]+(1-q)*list_vals[2*i+1])*discount_factor 
        expected_payoffs.append(exp_payoff);
        action=0;
        if list_vals[i]>exp_payoff:
            action=1;
        optimal_action.append(action);

    action_tree=binarytree.build(optimal_action);
    expectation_tree=binarytree.build(expected_payoffs)
    return action_tree,expectation_tree
コード例 #2
0
 def create_tree(self):
     tree = [
         self.S, self.d * self.S, self.u * self.S, self.d**2 * self.S,
         self.d * self.u * self.S, self.d * self.u * self.S,
         self.u**2 * self.S
     ]
     return build(tree)
コード例 #3
0
    def test_to_array_representation(self):
        array = self.empty_bst.to_array_representation()
        self.assertEqual(array, [])

        array = self.bst.to_array_representation()
        root = binarytree.build(array)
        self.assertEqual(array, root.values)
コード例 #4
0
    def print(self):
        current_level = [self]
        tree = list()
        global levels
        space = levels
        while current_level and space >= 1:
            for node in current_level:
                tree.append(node.value)

            next_level = list()
            for n in current_level:
                if n.left:
                    next_level.append(n.left)
                else:
                    next_level.append(BinaryNode(0))
                if n.right:
                    next_level.append(n.right)
                else:
                    next_level.append(BinaryNode(0))
                current_level = next_level
            space -= 1

        arbolInter = []
        for elemento in tree:
            if elemento == 0:
                arbolInter.append(None)
            else:
                arbolInter.append(elemento)

        tree = arbolInter
        root = binarynode.build(tree)
        print(root)
コード例 #5
0
def pprint_default(values):
    """Helper function for testing Node.pprint with default arguments."""
    root = build(values)
    with CaptureOutput() as output:
        root.pprint(index=False, delimiter="-")
    assert output[0] == "" and output[-1] == ""
    return [line for line in output if line != ""]
コード例 #6
0
def buildData(values=None, height=None, perfect=False):
    if values:
        btTree = bt.build(values)
    elif height:
        btTree = bt.tree(height=height, is_perfect=perfect)
    else:
        btTree = None

    def convert(btTree):
        if not btTree: return None
        values = btTree.values
        nodes = [BinTreeNode(values.pop(0))]
        root = nodes[0]

        while len(values) > 0:
            parent = nodes.pop(0)
            left = BinTreeNode(values.pop(0))
            right = BinTreeNode(values.pop(0) if len(values) > 0 else None)
            nodes.append(left)
            nodes.append(right)
            if parent and parent.val is not None:
                if left.val is not None: parent.left = left
                if right.val is not None: parent.right = right

        return root

    return (btTree, convert(btTree))
コード例 #7
0
def pprint_with_index(values):
    """Helper function for testing Node.pprint with indexes."""
    root = build(values)
    with CaptureOutput() as output:
        root.pprint(index=True, delimiter=":")
    assert output[0] == "" and output[-1] == ""
    return [line for line in output if line != ""]
コード例 #8
0
def builtin_print(values):
    """Helper function for testing builtin print on Node."""
    root = build(values)
    with CaptureOutput() as output:
        print(root)
    assert output[0] == "" and output[-1] == ""
    return [line for line in output if line != ""]
コード例 #9
0
def test_everything_match(my_tree):
    tree1 = my_tree
    values = [7, 3, 2, 6, 9, 10, 1, 5, 8]
    tree2 = build(values)

    assert BinaryTree.tree_intersection(tree1,
                                        tree2) == {7, 3, 2, 6, 9, 10, 1, 5, 8}
コード例 #10
0
def retrieve_LCA(tree_id, node1, node2):
    """Method to retrieve Last common ancester of 2 nodes in a Binary tree"""

    key = 'Binarytree.' + tree_id
    if key in storage.all("Binarytree").keys():

        list_rep = storage.all("Binarytree")[key].tree_list
        tree_inst = build(list_rep)

        path1, path2 = [], []

        exist1 = findpath(tree_inst, path1, node1)
        exist2 = findpath(tree_inst, path2, node2)

        if exist1 is False:
            return make_response(jsonify({"error": "Node1 Not found"}), 404)

        if exist2 is False:
            return make_response(jsonify({"error": "Node2 Not found"}), 404)

        L_C_A = LCA(path1, path2)

        if LCA is not None:
            return make_response(jsonify({"LCA": "{}".format(L_C_A)}), 200)
    else:
        abort(404)
コード例 #11
0
def build_heap(arr: list[int, None]) -> binarytree.Node:
    """
        Build heap tree using binarytree.build\n
        :param arr: list to build from\n
        :return: binarytree.Node
        """
    return binarytree.build(arr)
コード例 #12
0
def print_contract_tree(account, contract):
    root_value = call_function(account, contract, 'root')
    if root_value == 0:
        return
    root = call_function(account, contract, 'getNode', root_value)
    queue = [root]
    items = []
    while queue:
        current_item = queue[0]
        if current_item is None:
            items.append(None)
            queue.append(None)
            queue.append(None)
        else:
            items.append(current_item)
            left = None
            right = None
            if current_item[2] != 0:
                left = call_function(account, contract, 'getNode',
                                     current_item[2])
            if current_item[3] != 0:
                right = call_function(account, contract, 'getNode',
                                      current_item[3])
            queue.append(left)
            queue.append(right)
        queue = queue[1:]
        if all((x is None for x in queue)):
            break

    for i in range(len(items)):
        if items[i] is not None:
            items[i] = items[i][0]
    print(build(items))
コード例 #13
0
ファイル: map2tree.py プロジェクト: y4604567890/python-study
def sumTree(p):
    t = binarytree.build(p.values)
    for node in t.postorder:
        if node.left:
            node.value += node.left.value
        if node.right:
            node.value += node.right.value
    return t
コード例 #14
0
def build_min_heap(arr: list[int, None]) -> binarytree.Node:
    """
        Build min heap tree using binarytree.build\n
        :param arr: list to build from\n
        :return: binarytree.Node
        """
    heapq.heapify(arr)
    return binarytree.build(arr)
コード例 #15
0
def beginRounds(tournSize, tournPlayers, values):
    currentRound = 0
    playersLeft = len(tournPlayers)
    roundsLeft = 1

    while roundsLeft > 0:
        roundsLeft = int(math.log2(len(tournPlayers)))
        if roundsLeft == 1:
            currentRound = 'Final'
        elif roundsLeft == 2:
            currentRound = 'SemiFinal'
        elif roundsLeft == 3:
            currentRound = 'QuarterFinal'

        #Building the initial binary tree for the tournament from the given array of players and 0 spots
        #Printing the binarytree for current round
        tree = build(values)
        print(tree)
        if currentRound == 'Final':
            print(currentRound, 'Round match:')
        else:
            print(currentRound, 'Round matches:')

        k = 0
        j = 0
        matches = []
        while k < len(tournPlayers) / 2:
            matches.append([tournPlayers[j], tournPlayers[j + 1]])
            k = k + 1
            j = j + 2

        b = 0
        while len(tournPlayers) > b:
            first = b
            second = b + 1
            print((player.players[first])['name'], 'vs',
                  (player.players[second])['name'])
            b = b + 2

        loserArray = []
        for i in range(len(matches)):
            loser = random.choice(matches[i])
            loserArray.append(loser)
            matches[i].remove(loser)
            winner = (matches[i])[0]
            print(winner)
        x = len(loserArray)
        for i in range(x):
            tournPlayers.remove(loserArray[i])
            values.remove(loserArray[i])
        numZeros = len(tournPlayers)
        for i in range(numZeros):
            del (values[0])
        if roundsLeft == 1:
            roundsLeft = 0
            tournwinner = tournPlayers[-1]
            print("The winner is", (player.players[tournwinner - 1])['name'])
コード例 #16
0
ファイル: decision_tree.py プロジェクト: Knniff/treemaker
 def create_tree(self):
     base_tree = []
     for x in range(0, self.depth):
         times = 2 ** x
         for _ in range(times):
             base_tree.append(x + 1)
     base_tree.extend(self.result)
     tree = build(base_tree)
     return tree
コード例 #17
0
def buildTree(doprint = False):
    # First create a list with random values
    nodes = []
    for node in range((2**depth)-1):
        nodes.append(numpy.random.uniform(0, 100))
    # tNode and numberVisits added in the package itself, set to 0
    binary_tree = bt.build(nodes)
    if doprint:
        print('Binary tree from list :\n', binary_tree)
        print('\nList from binary tree :', binary_tree.values)
    return binary_tree
コード例 #18
0
def main():
    data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
            14, 15, 16]

    root = build(data)

    print(root)

    height = get_height(root)

    print('height: ', height)
コード例 #19
0
def test_given_2():
    tree = build([1, 2, 2, None, 3, None, 3])
    #      __1
    #     /   \
    #    2     2
    #     \     \
    #      3     3
    expected = False
    s = Solution()
    actual = s.isSymmetric(tree)
    assert actual == expected
コード例 #20
0
def my_tree():
    #         __7___
    #        /      \
    #     __3       _2
    #    /   \     /  \
    #   6     9   10   1
    #  / \
    # 5   8
    values = [7, 3, 2, 6, 9, 10, 1, 5, 8]
    root = build(values)
    return root
コード例 #21
0
def test_given_1():
    tree = build([1, 2, 2, 3, 4, 4, 3])
    #        __1__
    #       /     \
    #      2       2
    #     / \     / \
    #    3   4   4   3
    expected = True
    s = Solution()
    actual = s.isSymmetric(tree)
    assert actual == expected
コード例 #22
0
def my_tree2():
    #            ___10___
    #           /        \
    #      ___134        _5
    #     /      \      /  \
    #   _23       9    10   45
    #  /   \
    # 32    8

    values = [10, 134, 5, 23, 9, 10, 45, 32, 8]
    root = build(values)
    return root
コード例 #23
0
def ejercicio_d():
    values = ([
        'B', 'U', 'I', 'E', 'R', 'E', 'L', 'N', None, None, 'R', 'N', None,
        'B', None, 'O', 'A', None, None, None, None, 'A', 'O', None, None, 'A',
        None, None, None, None, None, None, 'S', None, None, None, None, None,
        None, None, None, None, None, 'S', None, None, None, None, None, 'O',
        None, None, None, None, None, None, None
    ])

    # ESTE EJERCICIO NO PUDE ACABARLO PORQUE NO SABIA COMO METER CARACTERES EN UN ARBOL BINARIO
    raiz = binarytree.build(values)

    print(raiz)
コード例 #24
0
    def construct_ref_bst_tree(target: BinarySearchTree):
        """Construct a reference tree identical to the given target tree and
        check if the generated tree is a binary search tree.

        Note:
            This function will add a random element to the given tree at the
            start of the function if the given tree is empty, to avoid raising
            errors when operating on an empty tree.
        """
        if not target.root:
            target.insert(randint(-100, 100))
        tree = build(target.list_repr)
        assert tree.is_bst
        assert len(target) == len(tree)
        return tree
コード例 #25
0
def test_tree_build():
    root = build([])
    assert root is None

    root = build([1])
    assert root.value == 1
    assert root.left is None
    assert root.right is None

    root = build([1, 2])
    assert root.value == 1
    assert root.left.value == 2
    assert root.right is None

    root = build([1, 2, 3])
    assert root.value == 1
    assert root.left.value == 2
    assert root.right.value == 3
    assert root.left.left is None
    assert root.left.right is None
    assert root.right.left is None
    assert root.right.right is None

    root = build([1, 2, 3, None, 4])
    assert root.value == 1
    assert root.left.value == 2
    assert root.right.value == 3
    assert root.left.left is None
    assert root.left.right.value == 4
    assert root.right.left is None
    assert root.right.right is None
    assert root.left.right.left is None
    assert root.left.right.right is None

    with pytest.raises(NodeNotFoundError) as err:
        build([None, 1, 2])
    assert str(err.value) == 'Parent node missing at index 0'

    with pytest.raises(NodeNotFoundError) as err:
        build([1, None, 2, 3, 4])
    assert str(err.value) == 'Parent node missing at index 1'
コード例 #26
0
 def test_random_binary_tree(self):
     for _ in range(10000):
         bt = random_binary_tree()
         if bt is not None:
             print_binary_tree(bt)
             vals = binary_tree_values(bt)
             print(vals)
             t = build(vals)
             self.assertEqual([e.val for e in t.preorder], preorder_array(bt))
             self.assertEqual([e.val for e in t.preorder], preorder_array_iterative(bt))
             self.assertEqual([e.val for e in t.inorder], inorder_array(bt))
             self.assertEqual([e.val for e in t.inorder], inorder_array_iterative(bt))
             self.assertEqual([e.val for e in t.postorder], postorder_array(bt))
             self.assertEqual([e.val for e in t.postorder], postorder_array_iterative(bt))
             self.assertEqual([e.val for e in t.levelorder], level_order_array(bt))
             self.assertEqual([e.val for e in t.levelorder], level_order_array_recursive(bt))
コード例 #27
0
def mirror():
    #Pass in any values to create a tree
    values = [7, 3, 2, 6, 9, 1, 5, 8]
    if len(values) == 1:
        print(values)
    elif len(values) == 0:
        print("None")
    else:
        tree1 = build(values)

        for i in range(len(tree1)):
            try:
                temp = tree1[i].left
                tree1[i].left = tree1[i].right
                tree1[i].right = temp
            except:
                print("no index")

        print(tree1)
 def test_1(self):
     values = [
         3, 6, 8, 2, 11, None, 13, None, None, 9, 5, None, None, 7, None
     ]
     root = build(values)
     #print(root)
     """
         _______3
        /        \
        6__        8__
        /   \          \
        2     11         13
            /  \       /
            9    5     7
     """
     self.assertEqual(3, lowest_common_ancestor(root, 2, 8).value)
     self.assertEqual(6, lowest_common_ancestor(root, 2, 5).value)
     self.assertEqual(11, lowest_common_ancestor(root, 9, 5).value)
     self.assertEqual(8, lowest_common_ancestor(root, 8, 7).value)
     self.assertEqual(3, lowest_common_ancestor(root, 9, 3).value)
コード例 #29
0
ファイル: IBRS.py プロジェクト: IBRS4VANETs/TEST-CASEs
  def __init__(self, kappa, btLevel, salt):
    """Generate a group and an empty tree
    :kappa: MNT159, SS512, SS1024
    :btLevel: the level of initial binary tree
    :salt: the salt to generate random-like nodes
    :self.N: the level of the tree
    :self.rest: available leaves in the tree
    :self.kunodes: a list to predict whether a node is revoked or not
    :self.bt: the binary tree
    """
    self.group = PairingGroup(kappa)
    self.P, self.Q, self.msk = self.group.random(G1), self.group.random(G2) ,self.group.random(ZR)

    self.PK1 = self.msk * self.P
    self.PK2 = self.msk * self.Q
    self.N = btLevel
    self.rest = list(range(2 ** btLevel))
    self.yellowPages = []

    def preHandle(ids, preNodes):
      if len(ids) == 1:
        return preNodes
      else:
        i = 0
        temp = []
        while i < len(ids):
          newNodes = hashlib.sha256((str(ids[i] + ids[i+1]) + salt).encode('utf-8'))
          temp.append(newNodes.hexdigest())
          # temp.append(ids[i] + ids[i+1])
          i += 2
        preNodes.append(temp)
        preHandle(temp, preNodes)

    basket = [str(x) for x in self.rest]
    retList = []
    preHandle(self.rest, basket)

    for i in basket[::-1]:
      retList.extend(i)
    self.bt = build([int(binascii.b2a_hex(x.encode('utf-8'))) for x in retList])
    self.kunodes = {self.bt.value}
コード例 #30
0
ファイル: avl.py プロジェクト: Sergei-Morozov/MIT-Algorithms
 def show_tree(self):
     from binarytree import build
     queue = Queue()
     queue.put(self.root)
     result = []
     while not queue.empty():
         item = queue.get()
         if item:
             result.append(item.value)
             if item.left:
                 queue.put(item.left)
             else:
                 queue.put(None)
             if item.right:
                 queue.put(item.right)
             else:
                 queue.put(None)
         else:
             result.append(item)
     print(result)
     print(build(result))