def unique_bst_q2_helper(start, end): bsts = [] if start > end: bsts.append(BinaryTree(None)) return bsts # current root is i for i in range(start, end + 1): # generate all left_subtrees, will return a list of all possible left subtrees left_subtrees = unique_bst_q2_helper(start, i - 1) # generate all right_subtrees, will return a list of all possible right subtrees right_subtrees = unique_bst_q2_helper(i + 1, end) # for each left subtree and each right subtree for j in range(len(left_subtrees)): for k in range(len(right_subtrees)): # current root is i curr_root = TreeNode(i) # connect curr_root to left subtree's root and right subtree's root curr_root.left = left_subtrees[j].root curr_root.right = right_subtrees[k].root # create a new bst using curr_root as root curr_bst = BinaryTree(curr_root) # append to the result bsts.append(curr_bst) return bsts
def get_tree(model, fe, index): tree = model.trees[index] fnames = model.Predictor.featureNames btree = BinaryTree() node_idx = 0 btree.root = get_tree_(node_idx, fe, tree, fnames, 1) return btree
def loadBinaryTree(words): tree = bt.BinaryTree() for key, word in words.items(): tree.insert(word, compWords) return tree
def get_tree(model, fe, index): tree = model.Trees()[index] fnames = model.FeatureNames() btree = BinaryTree() node_idx = 0 btree.root = get_tree_(node_idx, fe, tree, fnames, 1) return btree
def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeftChild('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRightChild('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() elif i not in ['+', '-', '*', '/', ')']: try: currentTree.setRootVal(int(i)) currentTree = pStack.pop() except ValueError: raise ValueError("token '{}' is not a valid integer".format(i)) return eTree
def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+', '-', '*', '/', ')']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
def buildParseTree(fpexp): """modified buildParsTree method to handle boolean operations""" fplist = tokenize(fpexp) #print(fplist) pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() #included and, or , not elif i not in ['+', '-', '*', '/', ')', 'and', 'or', 'not']: if i.isdigit(): #"i" is a number currentTree.setRootVal(int(i)) else: #"i" is not a number currentTree.setRootVal(i) parent = pStack.pop() currentTree = parent #included and, or, not elif i in ['+', '-', '*', '/', 'and', 'or', 'not']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
def tree_sort(a_list): start = time.time() r = BinaryTree.BinaryTree(a_list[0]) for x in range(len(a_list)): if x > 0: r.insert(a_list[x]) end = time.time() return end-start
def main(): testNum = [2, 3, 5, 4, 9, 6, 4, 7, 8, 1, 7, 2, 3, 4, 7, 2, 3, 5, 6, 4, 5] goal = np.array([4, 6, 7]) testArray = np.reshape(testNum, (7, 3)) tree = bt.BinaryTree(3) makeTree(tree, testArray) findNode(tree, goal, len(goal))
def createForest(fileInfo, uniqueArray): forest = list() for x in uniqueArray: leaf = BinaryTree(0, x) for y in fileInfo: if x == y: leaf.addWeight(1) forest.append(leaf) return forest
def build_tree(f): str_nwk = open(f).read().strip(';') # Newick_110.nwk stack_nwk = [] header = '' for i, c in enumerate(str_nwk): if c == ',': if header: # end of header, push a leaf tmp_node = BinaryTree.BinaryTree(header) tmp_node.set_seq(list(search_align_file(header))) # get sequence stack_nwk.append(tmp_node) header = '' elif c == ')': # new blank node if i == len(str_nwk) - 1: # the last ), left 3 nodes break if header: # push a leaf tmp_node = BinaryTree.BinaryTree(header) tmp_node.set_seq(list(search_align_file(header))) # get sequence stack_nwk.append(tmp_node) header = '' # if c.next == ';': break # print("before", stack_nwk) tmp_node = BinaryTree.BinaryTree(0) tmp_node.rightchild = stack_nwk.pop() tmp_node.leftchild = stack_nwk.pop() stack_nwk.pop() stack_nwk.append(tmp_node) # print("after",stack_nwk) elif c == '(': stack_nwk.append('(') else: # header header += c # 3 nodes left in stack # deal with tree nodes node_1 = stack_nwk.pop() node_2 = stack_nwk.pop() node_3 = stack_nwk.pop() return node_1, node_2, node_3
def __init__(self, frame, callback): # callback to send msgs back to caller self.callback = callback self.canvas = Canvas(frame, background="white", cursor="hand1") self.canvas.grid(row=0, column=0, sticky=NSEW) # insert horizontal scrollbar hscroll = Scrollbar(frame, orient=HORIZONTAL, command=self.canvas.xview) hscroll.grid(row=1, column=0, sticky=EW) self.canvas.configure(xscrollcommand=hscroll.set) self.selected = self.sel_rect = None self.tree = rbt.BinaryTree()
class main: datos = pd.read_csv("/Users/isabella/Documents/Segundo Semestre/Estructura de Datos y Algoritmos/Talleres/Códigos/Taller 10/personas-en-situacion-de-vulnerabilidad.csv") datosLimpios = datos.drop(["MI", "Agency", "Room", "Building"], axis = 1) arbol = bt.BinaryTree() for i in range(len(datosLimpios)): #print(datosLimpios["FirstName"].values[i], datosLimpios["LastName"].values[i], datosLimpios["PhoneNumber"].values[i]) person = Persona(datosLimpios["FirstName"].values[i], datosLimpios["LastName"].values[i], datosLimpios["PhoneNumber"].values[i]) arbol.insertar(person.data) arbol.borrar("wanda 301-504-7271 \n") arbol.imprimir() print(arbol.buscar('vivian brooks 301-504-1758')) print(arbol.buscar('Isabella Montoya 314-816-6711')) print(arbol.dibujar())
def start_test(self, type): results = np.zeros((50, 3)) for index, i in enumerate(self.bases): # create if type == 0: tree = BinaryTree() elif type == 1: tree = AVLTree() elif type == 2: tree = Treap() elif type == 3: tree = SplayTree() for e in self.dataset[0:i]: tree.insert(e) results[index, :] = self.test_tree(tree, type) return results
def creat(self, problem_number, r): creat_pro = CreatProblem.Create() t = BinaryTree.BinaryTree() c = Check.Check() with open("Exercises.txt", "w") as file1, open("Answer.txt", "w") as file2: num = 0 while num < problem_number: arith = creat_pro.create_arith(r) # 生成四则运算列表 Ju = CreateTree.Judge() al = Ju.toRPN(arith) # 将列表转换成逆波兰式 string = creat_pro.to_string(creat_pro.proper_fraction(arith)) ta = Ju.createTree(al) # 将逆波兰式生成规范二叉树 if ta: val = str(creat_pro.pop_fracte(ta.value)) if c.check_tree(t.to_string(ta)): # 进行判重 file1.write("%d. " % (num + 1) + string + '\n') file2.write("%d. " % (num + 1) + val + '\n') num += 1 print("四则运算题目生成完毕,数量为%d个" % problem_number)
def build_parse_tree(self, exp: str) -> str: # todo if not self.matched_expression(exp): return None t = BinaryTree.BinaryTree() t.r = t.Node('') u = t.r operators = ['+', '-', '*', '/', '(', ')'] for token in exp: if token == '(': u = u.insert_left() if token in '+-*/': u.x = token u = u.insert_right() if token.isalpha(): u.x = token u = u.parent if token == ')': u = u.parent return t
def buildHuffManTree(forest): while (len(forest) > 1): # already sorted tempNode1 = forest[0] tempNode2 = forest[1] totalWeight = tempNode1.weight + tempNode2.weight innerNode = BinaryTree(totalWeight, '@') # inner node if (tempNode1.weight >= tempNode2.weight): tempNode1.code = "1" innerNode.right = tempNode1 tempNode2.code = "0" innerNode.left = tempNode2 else: tempNode2.code = "1" innerNode.right = tempNode2 tempNode1.code = "0" innerNode.left = tempNode1 forest.append(innerNode) forest = forest[2:] forest = sortForest(forest) return forest
def put(self, key, value): precondition(True) t = self if(t.tree.getValueWithPath("") == ""): t.tree = BinaryTree([key, value]) self.__rep_inv__() return else: path = "" while(True): #check for duplicates if(key==t.tree.getValueWithPath(path)[0]): t.tree = t.tree.replaceValueWith(path, [key, value]) self.__rep_inv__() return #create the path for where value should go newPath = path if(key>t.tree.getValueWithPath(path)[0]): newPath=newPath+"r" elif(key<t.tree.getValueWithPath(path)[0]): newPath=newPath+"l" #Check if a value already exists there if(t.tree.nodeExists(newPath)): if(t.tree.getValueWithPath(newPath)==""): t.tree = t.tree.replaceValueWith(newPath, [key, value]) self.__rep_inv__() return else: path = newPath else: if(key>t.tree.getValueWithPath(path)): t.tree = t.tree.withNewBranches(path, "", [key, value]) self.__rep_inv__() return elif(key<t.tree.getValueWithPath(path)): t.tree = t.tree.withNewBranches(path, [key, value], "") self.__rep_inv__() return
def main(): bt = BinaryTree.BinaryTree() #creating an empty Binary Tree bt.buildTree("EmployeeList") #building the Binary Tree file_dict = {} #empty dictionary for the employeeID DNA to go into for filename in os.listdir( os.getcwd() + '\\Task One' ): #read in each ID#.txt and kid.txt with the ID# as the dictionary key for each dna strand with open(os.path.join(os.getcwd() + '\\Task One', filename)) as file_object: filename = filename.split( ".") #split to remove .txt from the dictionary key row = file_object.read() row = row.replace( "GAATTC", "G/AATTC" ) #cut the DNA strings using the 3 methods in assignment row = row.replace("GGATCC", "G/GATCC") row = row.replace("AAGCTT", "A/AGCTT") row = row.split("/") #split on the "/" after replacing rowList = [len(i) for i in row] #list comprehension file_dict[filename[0]] = rowList y = set(file_dict['kidDNA']) maxSize = 0 for key in file_dict: #looping through the employeeIds in file_dict if key != 'kidDNA': x = set(file_dict[key] ) #set algebra to compare the employee to the kidw z = x.intersection(y) if len(z) > maxSize: maxLength = key maxSize = len(z) bt.searchTree( bt.root, int(maxLength) ) #search tree for the EmployeeId that matched the most lengths
def main(): inputFile = 'Test0.txt' outputFile = 'Test0_output.txt' tree = BinaryTree.BinaryTree(inputFile) bst = BinarySearchTree.BinarySearchTree() # Binary Tree tests with open(outputFile, 'w') as f: f.write(' '.join( str(x) for x in tree.inOrderTraversal(tree.getRoot()))) f.write('\n') tree.clearTraversalResult() f.write(' '.join( str(x) for x in tree.preOrderTraversal(tree.getRoot()))) f.write('\n') tree.clearTraversalResult() f.write(' '.join( str(x) for x in tree.postOrderTraversal(tree.getRoot()))) f.write('\n') tree.clearTraversalResult() print(tree.isBST(tree.getRoot())) # Binary Search Tree tests root = bst.getRoot() root.addKey(random.randint(1, 1000000)) for x in random.sample(range(2, 10000000), 1000000): bst.addNode(root, x) print(bst.isBST(bst.getRoot())) sys.exit()
def binary_tree_upside_down(root): dummy_root = TreeNode(0) cousin = None while root: # record left and right left_child = root.left right_child = root.right # insert under dummy_root's right root.right = dummy_root.right dummy_root.right = root # connect left root.left = cousin # update cousin and root itself cousin = right_child root = left_child return dummy_root.right if __name__ == '__main__': t1 = BinaryTree() pre_order = [1, 2, 4, 5, 3] in_order = [4, 2, 5, 1, 3] r1 = t1.create_tree(pre_order, in_order) r2 = binary_tree_upside_down(r1) t2 = BinaryTree() t2.clone_tree(r2) t2.pre_order_print(r2) print t2.in_order_print(r2)
""" """ import BinaryTree as bt t1 = bt.BinaryTree([1, 2, 3, 4, 5, '#', 6, 7, '#', '#', '#', '#', 8]) t1.display()
nf = Node('F') ng = Node('G') nh = Node('H') nj = Node('J') nk = Node('K') root.left = nb root.right = nc nb.left = nd nb.right = ne nc.left = nf nc.right = ng nd.left = nh nf.right = nj BiTree = BinaryTree(root) def test_size(): assert BiTree.size() == 9 def test_depth(): assert BiTree.depth() == 4 def test_inorder(): assert BiTree.inorder() == ['H', 'D', 'B', 'E', 'A', 'F', 'J', 'C', 'G'] def test_preorder():
if dr + 1 == k: print str(root.data) + " ", else: nodes_at_dist_k_down(root.left, k - dr - 2) return 1 + dr #if n is not present in left or right subtree return -1 return -1 if __name__ == "__main__": # example 1 tree = b_tree.BinaryTree(20) root = tree.root root.left = b_tree.Node(8) root.right = b_tree.Node(22) root.left.left = b_tree.Node(4) root.left.right = b_tree.Node(12) root.left.right.left = b_tree.Node(10) root.left.right.right = b_tree.Node(14) print "All nodes at distance k in example 1: " t = 8 #target node with data k = 2 #find all nodes from t which are at distance k nodes_at_dist_k(root, t, k) print # example 2
def __init__(self): precondition(True) self.tree = BinaryTree("")
def adaboostTrain(self, data, discrete=True): if self._weakClsList is not None: print('Strong classifier has been trained.') return if not isinstance(discrete, bool): raise TypeError('bool type is required.') self.discrete = discrete if not data.quant: data.quantize() #train self._weakClsList = [] if discrete: self.weakClsWt = [] else: self.weakClsWt = None #for caculate loss function posCumCls = np.zeros(data.posWt.shape[0]) negCumCls = np.zeros(data.negWt.shape[0]) for i in range(self.clsNum): binaryTree = BinaryTree(**self.pTree) binaryTree.train(data) #if discrete adaboost, classfication output is 1, -1 if discrete: binaryTree.tree['hs'] = (binaryTree.tree['hs'] > 0) * 2.0 - 1 constant = np.e**10 / (1 + np.e**10) alpha = 5.0 if (binaryTree.err < 1 - constant) else \ -5.0 if (binaryTree.err > constant) else \ 0.5 * log((1 - binaryTree.err) / binaryTree.err) self.weakClsWt.append(alpha) else: alpha = 1.0 self._weakClsList.append(binaryTree) #use trained weak classifier to classify posResult = binaryTree.apply(data.posSamp) negResult = binaryTree.apply(data.negSamp) #update samples weight posCumCls += posResult * alpha negCumCls += negResult * alpha data.posWt = np.exp(-posCumCls) / data.posWt.shape[0] / 2 data.negWt = np.exp(negCumCls) / data.negWt.shape[0] / 2 #data.posWt *= np.exp(-alpha * posResult) #data.negWt *= np.exp(alpha * negResult) #loss function loss = np.sum(data.posWt) + np.sum(data.negWt) print('weak classifier%d: err = %s, alpha = %s, loss = %s' % (i, format(binaryTree.err, '.3e'), format( alpha, '.3e'), format(loss, '.3e'))) #samples weight normalization data.posWt /= loss data.negWt /= loss #overfit? if loss <= 1e-40: print('Stop early.') self.clsNum = i + 1 break #apply decsion forest def apply(self, data): """ data -the arrays represent the fearture of img patch(es) """ if self._weakClsList is None: raise Exception('strong classifier is not trained.') clsResults = np.zeros(data.shape[0], 'float64') if self.discrete: for i in self.clsNum: clsResults += (self.weakClsWt[i] * self._weakClsList[i].apply(data)) else: for i in self.clsNum: clsResults += self._weakClsList[i].apply(data) return clsResults
sys.path.append("E:/code") from BinaryTree import * def inorder(root): # 使用栈记录搜索路标 stack = [] cur = root # 记录输出节点顺序 nodes = [] while len(stack) > 0 or cur: # 一直搜索左孩子 if cur: stack.append(cur) cur = cur.left else: # 搜索到尽头后输出节点 cur = stack.pop() nodes.append(cur) right = cur.right # 清空输出的节点, 也可以不删 cur.left = None cur.right = None cur = right return nodes if __name__ == "__main__": a = BinaryTree([1, 3, 2, 5, 4, 6]) nodes = inorder(a.root) print([each.value for each in nodes])
return False tree_1_left = tree1.get_left() tree_2_left = tree2.get_left() tree_1_right = tree1.get_right() tree_2_right = tree2.get_right() #Check if the left subtrees are equal and if the right subtrees are equal if is_equal(tree_1_left, tree_2_left) and is_equal(tree_1_right, tree_2_right): return True return False tree1 = BinaryTree() tree1.insert(10) tree1.insert(8) tree1.insert(15) tree1.insert(14) tree1.print() tree2 = BinaryTree() tree2.insert(10) tree2.insert(8) tree2.insert(15) tree2.insert(14) tree2.print() print("Are these binary trees equal?", is_equal(tree1.get_root(), tree2.get_root()))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 22 21:03:03 2017 @author: bhumihar """ import BinaryTree binary_tree = BinaryTree.BinaryTree(1) binary_tree.insert_data(2) binary_tree.insert_data(3) binary_tree.insert_data(4) binary_tree.insert_data(5) binary_tree.insert_data(6) binary_tree.insert_data(7) #binary_tree.insert_data(8) #binary_tree.insert_data(9) #binary_tree.insert_data(10) #binary_tree.insert_data(11) #binary_tree.insert_data(12) #binary_tree.insert_data(13) root = binary_tree.get_root() print('####Preorder Recursion Transversal####') print(binary_tree.preorder_transversal(root)) print('####Preorder Without Recursion Transversal####') print(binary_tree.preorder_wr_transversal(root))
# -*-coding:utf-8 -*- # *-*Author:DreamYee*-* # Create:2019/09/11 21:43 # File:DemoC-二叉树.py import BinaryTree root = BinaryTree.BinaryTree('root') b = root.insertRightChild('B') a = root.insertLeftChild('A') c = a.insertLeftChild('C') d = c.insertRightChild('D') e = b.insertRightChild('E') f = e.insertLeftChild('F') print(root.inOrder()) print(root.postOrder()) print(b.inOrder())