def insert(self, key: int) -> bool: if self.__root is None: self.__root = Node(key) return True current = self.__root while True: if current.key == key: # node has same key does not allowed in BTS. return False parent = current # happened when the new key is smaller than the root of a sub-tree. should_go_left = current.key > key if should_go_left: current = current.left else: current = current.right if current is None: new_node = Node(key, parent) if should_go_left: parent.left = new_node else: parent.right = new_node self.__re_balance(parent) break return True
def preorder_to_bst(l): if not l: return None ro = Node(l[0]) ro.l = preorder_to_bst([e for e in l if e < l[0]]) ro.r = preorder_to_bst([e for e in l if e > l[0]]) return ro
def main(): root = Node(data=1) root = add_right(2, root) root.right = add_right(5, root.right) root.right.right = add_right(6, root.right.right) root.right.right = add_left(3, root.right.right) root.right.right.left = add_right(4, root.right.right.left) post_order(root) print()
def _insert(self, key, value, currentNode): """Insert helper method.""" if key < currentNode.key: if currentNode.hasLeftChild(): self._insert(key, value, currentNode.leftChild) else: currentNode.leftChild = Node(key, value, parent=currentNode) else: if currentNode.hasRightChild(): self._insert(key, value, currentNode.rightChild) else: currentNode.rightChild = Node(key, value, parent=currentNode)
def insert(self, key, value): """Insert a new node into tree.""" if self.root: self._insert(key, value, self.root) else: self.root = Node(key, value) self.size += 1
def make_node_queue(nList): queue = [] for cell in nList: print(str(cell[0]) + " " + str(cell[1])) n = Node(cell[0], cell[1]) queue.append(n) return queue
class ArvoreDecisao(): def fit(self, X, y, min_leaf = 5): self.dtree = Node(X, y, np.array(np.arange(len(y))), min_leaf) return self def predict(self, X): return self.dtree.predict(X)
def __init__(self, competitors): self.competitors = competitors self.actual_round_id = 0 self.rounds = [ Node(left_child=competitors[0], right_child=competitors[1]) for i in range(2) ] self.final = None self.is_end = False
def get_topn_nodes(tag_dict, parent_node): """Get top N nodes based on tag probabilities""" top_n = [] dictsum = sum(tag_dict.values()) for tag_pair in sorted(tag_dict.items(), key=itemgetter(1), reverse=True)[:config.TOPN]: new_node = Node(tag_pair[0], parent_node, tag_pair[1]/dictsum, np.math.log(tag_pair[1]/dictsum, 10) + parent_node.cum_log_prob) top_n.append(new_node) return top_n
def tree_dfs_builder(records, node_builder, children_splitter, max_depth, curr_depth, child_id, continue_deepening): """ Build a tree in a dfs manner. records - list of elements that we are working on a current level node_builder(records, curr_depth, child_id) - procedure that builds content of a node based on a subset of records children_splitter(records, curr_depth, child_id) - how to split the elements amongst the children max_depth - when this depth is reached, then stop building further depths curr_depth - current depth of a current node child_id - identifier, which lets node_builder and children_splitter distinguish the important data in the records that are being passed; it's up to the user how to use this information continue_deepening(child_id) - function that answers to a question whether a child_id should be further divided """ PRINTER("[tree_dfs_builder]: depth: " + str(curr_depth) + " child_id: " + str(child_id)) PRINTER("[tree_dfs_builder]: creating a root node...") node = Node() node.content = node_builder(records, curr_depth, child_id) #PRINTER("[tree_dfs_builder]: node.content"+str(node.content)) #PRINTER("[tree_dfs_builder]: for each child of a child: "+str(child_id)+" "+str(continue_deepening(child_id))) if curr_depth == 0 or (curr_depth < max_depth and continue_deepening(child_id)): PRINTER("[tree_dfs_builder]: splitting child data for child_id: " + str(child_id)) child_data = children_splitter(records, curr_depth, child_id) #PRINTER("[tree_dfs_builder]: child_data"+str(child_data)) node.children = {} #for each child=classification code on that level for child_id in child_data.iterkeys(): #PRINTER("[tree_dfs_builder]: child_id"+child_id) node.children[child_id] = tree_dfs_builder( child_data[child_id], node_builder, children_splitter, max_depth, curr_depth + 1, child_id, continue_deepening) return node
def __rotate_right(self, a: Node) -> Node: b = a.left b.parent = a.parent a.left = b.right if a.left is not None: a.left.parent = a b.right = a a.parent = b if b.parent is not None: if b.parent.right != a: b.parent.left = b else: b.parent.right = b self.__set_balances(a, b) return b
def simulate(self): """ Run G consecutive games (aka. episodes) of the self.game_type using fixed values for the game parameters: N and K for NIM, B_init for Ledge. When the G games have finished, your simulator must summarize the win-loss statistics. A typical summary (for G = 50) would be a simple statement such as: Player 1 wins 40 of 50 games (80%). """ wins = 0 # Number of times player 1 wins # Actual games being played for episode in range(1, self.episodes + 1): logging.info("Episode: {}".format(episode)) # The actual game being played this episode game = get_new_game(self.game_type, self.game_config, verbose=self.verbose) # For each game, a new Monte Carlo Search Tree is made mcts = MonteCarloSearchTree(self.game_type, self.game_config) state, player = game.get_current_state(), self.get_start_player() mcts.set_root(Node(state, None, player=player)) # While the actual game is not finished while not game.is_winning_state(): # Every time we shall select a new action, we perform M number of simulations in MCTS for _ in range(self.num_sim): # One iteration of Monte Carlo Tree Search consists of four steps # 1. Selection leaf = mcts.selection() # 2. Expand selected leaf node sim_node = mcts.expansion(leaf) # 3. Simulation z = mcts.simulation(sim_node) # 4. Backward propagation mcts.backward(sim_node, z) # Now use the search tree to choose next action new_root = mcts.select_actual_action(player) # Perform this action, moving the game from state s -> s´ game.perform_action(player, new_root.action) # Update player player = get_next_player(player) # Set new root of MCST mcts.set_root(new_root) # If next player is 2 and we are in a win state, player 1 got us in a win state if player == 2: wins += 1 # Report statistics logging.info("Player1 wins {} of {} games ({}%)".format( wins, self.episodes, round(100 * (wins / self.episodes))))
def __insert(self, root, vti): if not root: return Node(vti) if vti <= root.value: root.left = self.__insert(root.left, vti) else: root.right = self.__insert(root.right, vti) return root
def tree_dfs_builder(records, node_builder, children_splitter, max_depth, curr_depth, child_id, continue_deepening): """ Build a tree in a dfs manner. records - list of elements that we are working on a current level node_builder(records, curr_depth, child_id) - procedure that builds content of a node based on a subset of records children_splitter(records, curr_depth, child_id) - how to split the elements amongst the children max_depth - when this depth is reached, then stop building further depths curr_depth - current depth of a current node child_id - identifier, which lets node_builder and children_splitter distinguish the important data in the records that are being passed; it's up to the user how to use this information continue_deepening(child_id) - function that answers to a question whether a child_id should be further divided """ PRINTER("[tree_dfs_builder]: depth: "+str(curr_depth)+" child_id: "+str(child_id)) PRINTER("[tree_dfs_builder]: creating a root node...") node = Node() node.content = node_builder(records, curr_depth, child_id) #PRINTER("[tree_dfs_builder]: node.content"+str(node.content)) #PRINTER("[tree_dfs_builder]: for each child of a child: "+str(child_id)+" "+str(continue_deepening(child_id))) if curr_depth == 0 or (curr_depth < max_depth and continue_deepening(child_id)): PRINTER("[tree_dfs_builder]: splitting child data for child_id: "+str(child_id)) child_data = children_splitter(records, curr_depth, child_id) #PRINTER("[tree_dfs_builder]: child_data"+str(child_data)) node.children = {} #for each child=classification code on that level for child_id in child_data.iterkeys(): #PRINTER("[tree_dfs_builder]: child_id"+child_id) node.children[child_id] = tree_dfs_builder(child_data[child_id], node_builder, children_splitter, max_depth, curr_depth+1, child_id, continue_deepening) return node
def get_child_nodes(self, state): """ Given the state, return all child nodes possible :param state: :return: """ legal_actions = self.game.get_legal_actions(state) new_states = [ self.game.get_next_state(state, action) for action in legal_actions ] return [ Node(state, action) for state, action in zip(new_states, legal_actions) ]
def _insert(self, val, node): """ a basic recursive function for insertion: * insert a node at a leaf node that found by binary searching for the right place for the value. * doesn't maintain the balance of the tree """ if node == None: return Node(val, None, None) else: if node.val > val: node.left = self._insert(val, node.left) elif node.val < val: node.right = self._insert(val, node.right) return node
def main(): tree = BinarySearchTree() """ data = [7, 1, 2, 3, 4, 5, 6, 8] data = [1, 2, 5, 3, 6, 4] t = 6 for i in range(t): x = data[i] tree.create(x) """ tree.root = Node(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) tree.root.right.left = Node(6) tree.root.right.right = Node(7) top_view(tree.root)
def __delete(self, node: Node) -> None: if node.left is None and node.right is None: if node.parent is None: # if tree has only root node. self.__root = None else: parent = node.parent # disconnect node and its parent. if parent.left is node: parent.left = None else: parent.right = None self.__re_balance(parent) return if node.left is not None: # child is the root of the left sub-tree of node. child = node.left # find the node which has the biggest key in the sub-tree. while child.right is not None: child = child.right else: # child is the root of the right sub-tree of node. child = node.right # find the node which has the smallest key in the sub-tree. while child.left is not None: child = child.left # copy the child's key of the sub-tree to the deleted place. node.key = child.key # remove the child whose value has already been copied to another place. self.__delete(child)
def build_tree(presentation): #init new tree huffmanT = HuffmanTree() #check if presentation length is even chars = presentation.keys() if len(chars) % 2 == 1: values = presentation.values() presentation[None] = max(values) + 1 #sort the key by values sortedP = sort_dic(presentation) nodeQueue = make_node_queue(sortedP) while (1 < len(nodeQueue)): n1 = nodeQueue.pop() n2 = nodeQueue.pop() # print("lson " + str(n1.get_count()) + " rson " + str(n2.get_count())) father = Node("", 0, n1, n2) nodeQueue.append(father) # print("father " + str(father.get_count())) #sort queue sort_queue(nodeQueue) huffmanT.set_root(nodeQueue.pop()) huffmanT.set_presentation(huffmanT.get_root()) return huffmanT
def __rotate_right_then_left(self, target: Node) -> Node: target.right = self.__rotate_right(target.right) return self.__rotate_left(target)
def has_next(self): if len(self.cache) > 0: return True else: return False def get_next(self): output_node = self.cache.pop() if output_node.left is not None: current_node = output_node.left self.cache.append(current_node) while current_node.right is not None: self.cache.append(current_node.right) current_node = current_node.right return output_node node1 = Node(2) node2 = Node(3) node12 = Node(1, node1, node2) node3 = Node(7) node03 = Node(9, None, node3) node_root = Node(6, node12, node03) x = postorder(node_root) while x.has_next(): print x.get_next().value
def __init__(self, competitor1, competitor2): self.round = Node(left_child=competitor1, right_child=competitor2)
def fit(self, X, y, min_leaf = 5): self.dtree = Node(X, y, np.array(np.arange(len(y))), min_leaf) return self
from typing import List from tree_node import Node class Solution: def __init__(self): self.result = [] def preorder(self, root: Node) -> List[int]: if root is None: return self.result.append(root.val) if root.children is not None: for node in root.children: self.preorder(node) return self.result if __name__ == '__main__': root = Node(val=1, children=[ Node(val=3, children=[ Node(val=5, children=None), Node(val=6, children=None) ]), Node(val=2, children=None), Node(val=4, children=None) ]) print(Solution().preorder(root=None))
def __init__(self, root_value=5): self.root = Node(root_value) self.node_count = 1 self.level = 0
# Declare all variables TEST_FILE = sys.argv[1] BOUNDARY_FILE = sys.argv[2] MODEL_FILE = sys.argv[3] SYS_OUTPUT = sys.argv[4] config.BEAM_SIZE = int(sys.argv[5]) config.TOPN = int(sys.argv[6]) config.TOPK = int(sys.argv[7]) data = FileParser(TEST_FILE, BOUNDARY_FILE, MODEL_FILE) # Beam search for sent_idx in range(len(data.test_set)): total_paths = {} data.final_probs[sent_idx] = {} root = Node('BOS', None, None, 0) history = copy.deepcopy(data.test_set[sent_idx][0][1]) tag1 = 'prevTwoTags=BOS+BOS' tag2 = 'prevT=BOS' base_weights = calc_base_weights(data.weights, data.tagset, history) tag_dict = calc_tag_probs(data.weights, base_weights, tag1, tag2) top_n = get_topn_nodes(tag_dict, root) pruned_nodes = prune_nodes(top_n, total_paths) data.final_probs[sent_idx][0] = get_class_label(pruned_nodes) for word_idx in range(1, data.sentence_lengths[sent_idx]): nodelist = [] history = copy.deepcopy(data.test_set[sent_idx][word_idx][1]) base_weights = calc_base_weights(data.weights, data.tagset, history) for node in total_paths[word_idx - 1]:
height """ from tree_node import Node # Get tree height def get_height(root): if root is None: return 0 left = get_height(root.left) right = get_height(root.right) return 1 + max(left, right) if __name__ == '__main__': root = Node(10) root.left = Node(7) root.right = Node(8) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(5) root.right.right = Node(7) root.left.left.left = Node(-1) root.left.right.right = Node(2) root.left.right.right.right = Node(4) print(get_height(root))