def __init__(self, fileName): self.tokens = [] self.pif = [] self.st = BST() self.fileName = fileName self.pifout = open("pif.txt", 'w') self.stout = open("st.txt", 'w')
def populate(n): randomList = [] bstList = BST() for i in range(0, n): randomList.append(random.randint(0, n)) bstList.append(random.randint(0, n)) return (randomList, bstList)
def populate(n): myList = [] myBST = BST() while len(myList) != n: randNum = (random.randrange(0, n + 1)) myList.append(randNum) myBST.append(randNum) return (myList, myBST)
def buildAllBST(self): allBST = [] # liste de tous les arbres for att in self.data[0].keys(): # Pour chaque argument, on crée un arbre a = BST() for dico in self.data: # Pour chacun des Dictionnaires, on ajoute l'argument 'att' dans l'arbre node = Node(dico[att], self.data.index(dico)) a.addNode(node) allBST.append(a) return allBST
def constructTree2(): tree = BST() tree.insert(4) tree.insert(1) tree.insert(7) tree.insert(6) tree.insert(5) tree.insert(2) tree.insert(3) return tree
def populate(n): randomList = [] bst = BST() for i in range(0, n): randomInt = random.randint(0, n) randomList.append(randomInt) bst.append(randomInt) return [randomList, bst]
class Directory: def __init__(self): self.numericalTree = BST() self.alphabeticalTree = BST() def DirectoryAddinput(self): name = input("Ingrese el nombre:") number = input("Ingrese el número:") wasAddedNumerically = self.numericalTree.addNumerically( Node(Contact(name, number))) wasAddedAlphabetically = self.alphabeticalTree.addAlphabetically( Node(Contact(name, number))) if (wasAddedNumerically and wasAddedAlphabetically): input("El contacto %s: %s fue agregado exitosamente." % (name, number)) else: input("El contacto %s: %s ya existe" % (name, number)) def mainMenu(self): menu = """Directorio de Contactos: 1.Agregar Contacto 2.Buscar Contacto 3.Borrar Contacto 4.Mostrar Contactos 5.Salir """ Keep = True while (Keep): print("\n" + menu) eleccion = input("Elige: ") if eleccion is "1": print("Insertar") elif eleccion is "2": print("Ver") elif eleccion is "3": print("Actualizar") elif eleccion is "4": print("Eliminar") elif eleccion is "5": print("Salir") Keep = False else: #Equivalente a 'default' print("Ninguna opción válida seleccionada")
def main(): mytree = BST() mytree.insert(3) mytree.insert(5) mytree.insert(2) mytree.insert(7) mytree.insert(12) mytree.insert(8) print "Is the tree balanced? ", IsBalancedTree(mytree)
def main(): # initialize a binary search tree bst = BST() bst.insert(3) bst.insert(5) bst.insert(2) bst.insert(7) bst.insert(12) bst.insert(8) print isBST1(bst.root) print isBST2(bst.root)
def test_add_node_int(self): int_bst = BST() int_bst.add_node(1) int_bst.add_node(2) int_bst.add_node(3) self.assertEqual(1, int_bst.find_node(1).key) self.assertEqual(2, int_bst.find_node(2).key) self.assertEqual(3, int_bst.find_node(3).key) self.assertIsNone(int_bst.find_node(4))
def test_find_node(self): int_bst = BST() # testing trying to find a node when no nodes are on BST self.assertIsNone(int_bst.find_node(1)) # adding the node of int 1 to the tree, then attempting to find this node int_bst.add_node(1) int_bst.add_node(5) int_bst.add_node(3) self.assertEqual(1, int_bst.find_node(1).key) self.assertEqual(5, int_bst.find_node(5).key) self.assertEqual(3, int_bst.find_node(3).key) self.assertIsNone(int_bst.find_node(2)) self.assertIsNone(int_bst.find_node(4))
def test_add_node_string(self): string_bst = BST() string_bst.add_node("string a") string_bst.add_node("string b") string_bst.add_node("string c") string_bst.add_node("string c") # adding repeat value self.assertEqual("string a", string_bst.find_node("string a").key) self.assertEqual("string b", string_bst.find_node("string b").key) self.assertEqual("string b", string_bst.find_node("string b").key) self.assertIsNone(string_bst.find_node("string d"))
def full_binary_tree(): test_tree = BST() test_tree.insert(5) test_tree.insert(8) test_tree.insert(9) test_tree.insert(2) test_tree.insert(4) return test_tree
def findSimilarityC(T, L): """ Search through the BST to find each one of the paired words provided by the user. Once both words are found, retrieve their corresponding embeddings and use the cosine distance to calculate and return their similarity. """ first_word = BST.search(T, L[0]) second_word = BST.search(T, L[1]) first_emb = first_word.emb second_emb = second_word.emb dot_product = np.dot(first_emb, second_emb) magnitude = np.linalg.norm(first_emb) * np.linalg.norm(second_emb) similarity = dot_product / magnitude return similarity
def main(): #init test a = [i for i in range(10000)] #bst init time t1 = time.time() bst = BST.binary_search_tree(a) t2 = time.time() print("It takes {:.2f}s for binary_search_tree init".format(t2 - t1)) t1 = time.time() rbt = red_black_tree.red_black_tree(a) t2 = time.time() print("It takes {:.2f}s for red_black_tree init".format(t2 - t1)) #test query t1 = time.time() if bst.iterative_query(50).key != None: print("Founded") t2 = time.time() print("It takes {:.6f}s for query 5000 in binary_search_tree".format(t2 - t1)) t1 = time.time() if rbt.iterative_query(50).key != None: print("Founded") t2 = time.time() print("It takes {:.6f}s for query 5000 in red_black_tree".format(t2 - t1))
def populate(n): if (isinstance(n, int)): if (n < 0): raise Exception('n has to be a positive integer') else: newList = [] newBST = BST() for i in range(0, n): randInt = random.randint(0, n) newList.append(randInt) newBST.append(randInt) return (newList, newBST) else: raise Exception('n has to be an integer')
def update_q(state, action, new_q): state = str(state) action = str(action) actionBST = q_values.findval(state, False) if not actionBST: actionBST = BST.Node(str([]), 0) q_values.insert(state, actionBST) actionBST.update(action, new_q)
def makeTree(self): self.tree = BST.BST(7) root = self.tree.root self.tree.insert(4) self.tree.insert(1) self.tree.insert(5) self.tree.insert(8) self.tree.insert(7.5)
def constructTree(preorderArray): stack = [] root = BST.BinaryTreeNode(preorderArray[0]) stack.append(root) for value in preorderArray[1:]: if value < stack[-1].data: new_left_node = BST.BinaryTreeNode(value) stack[-1].left = new_left_node stack.append(new_left_node) else: while stack and stack[-1].data < value: last = stack.pop() last.right = BST.BinaryTreeNode(value) stack.append(last.right) return root
def main(): nums = [ 10, 50, 100, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000 ] generate_tree(nums) for opt in range(3): if opt == 0: T = BST() elif opt == 1: T = AVL() elif opt == 2: T = BTree() file_name = '../test/' + T.__class__.__name__ + '.pkl' if os.path.exists(file_name): continue res = [] for n in nums: tree = extract_tree_element(n) for v in tree: T.insert(v) cnt = 0 for v in tree: cnt += T.search(v) avg = cnt / n res.append(avg) with open(file_name, 'wb') as f: pickle.dump(res, f) f.close() plot()
def BalancedBST(a,start,end): #IMPORTANT: exit condition > (not == or <) if start > end: return None mid = start + (end-start)//2 node = BST.BSTNode(a[mid]) node.left = BalancedBST(a,start,mid-1) node.right = BalancedBST(a,mid+1,end) return node
def constructBST(sortedArr): if len(sortedArr) <= 0: return None middle_distance = len(sortedArr) // 2 middle_element = sortedArr[middle_distance] root = BST.BinaryTreeNode(middle_element) root.left = constructBST(sortedArr[:middle_distance]) root.right = constructBST(sortedArr[middle_distance + 1:]) return root
def __init__(self, Numbers, Canvas): #初始化Do_BSTree类 Numbers.sort() self.The_BST = BST.BST(Numbers[0]) self.The_BST.Arrange_Numbers(Numbers) self.The_BST.root = self.The_BST.Create_BST() self.The_Canvas = Canvas self.The_Lines = [] self.The_Ovals = [] self.The_Texts = []
def main(): # initialize a binary search tree bst1 = BST() bst1.insert(7) bst1.insert(3) bst1.insert(8) bst1.insert(5) bst1.insert(2) bst1.insert(12) # the tree is like # 7 # / \ # 3 8 # / \ / # 2 5 12 findPath(bst1.root, 8)
def flattenBST(root): global prev if root is None: return dummy = BST.BinaryTreeNode(-1) prev = dummy flattenBSTHelper(root) prev.left = None prev.right = None ret = dummy.right return ret
def main(): # initialize a binary search tree bst = BST() bst.insert(7) bst.insert(3) bst.insert(8) bst.insert(5) bst.insert(2) bst.insert(12) # the tree is like # 7 # / \ # 3 8 # / \ / # 2 5 12 print "LCA of 2 and 12 is: ", findLCA(2, 12, bst.root).value print "LCA of 2 and 5 is: ", findLCA(2, 5, bst.root).value
def findSimilarityA(T, file): """ Read through the text file to retrieve each pair of words to be searched in a BST. Once both words are found, retrieve their corresponding embeddings and use the cosine distance to calculate their similarity. Store the similarity for each pair of words in the file in a list and return that list. """ L = [] for line in file: word_line = line.strip() word_pair = word_line.split(' ') first_word = BST.search(T, word_pair[0]) second_word = BST.search(T, word_pair[1]) first_emb = first_word.emb second_emb = second_word.emb dot_product = np.dot(first_emb, second_emb) magnitude = np.linalg.norm(first_emb) * np.linalg.norm(second_emb) similarity = dot_product / magnitude L.append(round(similarity, 4)) return L
def sendval(): global count global r if request.method == 'POST': val = request.args.get('val') text = request.args.get('text') text = nltk.word_tokenize(text) tagged_word = nltk.pos_tag(text) nouns_list = [] for i in tagged_word: if i[1][:2] == 'NN': nouns_list.append(i[0]) if count == 0: r = BST.Node(val, nouns_list) else: r = BST.insert(r, val, nouns_list) count += 1 my_pickle = open("BST_root.pickle", "wb") pickle.dump(r, my_pickle) my_pickle.close() return {val: nouns_list}
def balance_bst(bst): # validation check if bst == None: print("Tree doesn't contain any nodes") return # local variables bst_inorder = get_bst_inorder(bst.root) new_tree = BST.BST() # helper function that will recursively split the "bst_inorder" list by 2 # and append the middle value of each of the half list to the newly created tree def build_balanced_tree(root, start_idx, end_idx): # base case to have the recursion bottom out. # 1. Ensure the start_idx is always less than the end_idx # 2. If indices are the same, then this is the last # element that needs to be inserted in to the tree if start_idx > end_idx: return if start_idx == end_idx: insert_node(new_tree, bst_inorder[start_idx]) else: # compute the midpoint of the current list and use that value to build the tree mid_point = (start_idx + end_idx) // 2 # append the current mid value insert_node(new_tree, bst_inorder[mid_point]) # recursively work on the left half of the list build_balanced_tree(new_tree, start_idx, mid_point - 1) # do the same for the right side of the list build_balanced_tree(new_tree, mid_point + 1, end_idx) # call the helper function to get the fun started build_balanced_tree(new_tree, 0, len(bst_inorder) - 1) # return the new tree return new_tree
def getHeight(node): if node is None: return False else: marker = BST.Node() node.key = 323233223 queue = Queue.Queue() queue.enqueue(node) queue.enqueue(marker) count = -1 while not queue.isempty(): temp = queue.dequeue() if temp == marker: count += 1 if not queue.isempty(): queue.enqueue(marker) else: if temp.left is not None: queue.enqueue(temp.left) if temp.right is not None: queue.enqueue(temp.right) return count
#Question: Delete a node from Binary Search Tree(BST) import sys sys.path.append("./mylib") import BinaryTreeTraversal import BST a = [3,2,1,5,5,4,7] #Create BST root = BST.BSTNode(a[0]) for i in range(1,len(a)): node = BST.BSTNode(a[i]) BST.insert(root,node) print("Tree in-order traversal:") BinaryTreeTraversal.inOrder(root) #Time Complexity: O(logn), since only branch of a tree is processed #Delete node from BST print("\ndeleting node.data=", 3) root = BST.delete(root,BST.BSTNode(3)) print("Tree in-order traversal:") BinaryTreeTraversal.inOrder(root) print("")
#in-order traversal and list to store smallest K elements #Time complexity: O(n) #Space complexity: O(k) def KSmallest(root,k,mylist): if (len(mylist) < k and root.left is not None): KSmallest(root.left, k, mylist) if (len(mylist) < k): mylist.append(root.data) if (len(mylist) < k and root.right is not None): KSmallest(root.right, k, mylist) #Create BST root = BST.BSTNode(4) input = [3,2,1,5,6,7] for x in input: BST.insertNode(root, BST.BSTNode(x)) #Smallest K # mylist = [] # for x in range(1,len(input)+2): # KSmallest(root,x,mylist) # print("smallest element (k=%d) = %d" % (x,mylist.pop())) # del mylist[:] #Solution 3 #Reference: http://stackoverflow.com/questions/2329171/find-kth-smallest-element-in-a-binary-search-tree-in-optimum-way #Algorithm: #Step 1: Augment BST to store #nodes in its left subtree including current node #Step 2: Recursively traverse left or right subtree comparing k and #nodes in left subtree #Time complexity: O(log n) - depth of a node #Space complexity: O(1)
import sys sys.path.insert(0, '../') from BST import * import time print "" print "*********************************************************************" print "**************** DEMO 2 (Part a.): 1000 Puts in BST *****************" print "*********************************************************************" print "" print "" print " Operation Done: for i in range(1000): bst.put(i,i)" print "" print "" var = raw_input("Please press any key to go on: ") ht = BST() for i in range(1000): ht.put(i, i)
return node.data #case 2: node a and b are on the left subtree elif node.data >= anode.data and node.data >= bnode.data: return node.data #case 3: node a and b are on the right subtree elif node.data <= anode.data and node.data <= bnode.data: return node.data #case 4: go left elif node.data >= anode.data and node.data >= bnode.data: node = node.left #case 5: go right else: node = node.right a = [3,2,1,6,5,4,7] #Create BST root = BST.BSTNode(a[0]) for i in range(1,len(a)): node = BST.BSTNode(a[i]) BST.insert(root,node) print("In order traversal >>") BinaryTreeTraversal.inOrder(root) print("") node1 = BST.BSTNode(2) node2 = BST.BSTNode(4) print("LCA for nodes with values %d & %d = %d" % (node1.data,node2.data,findLCA(root,node1,node2))) print("LCA for nodes with values %d & %d = %d" % (node1.data,node2.data,findLCA2(root,node1,node2)))
def FindCombinations(node): result = [] lnodes = [] rnodes = [] #get root prefix = [node.data] #get all left nodes of the root FindChildNodes(node.left, lnodes) #get all right nodes of the root FindChildNodes(node.right, rnodes) #find permutations weave(lnodes,rnodes,result,prefix) return result import sys sys.path.append("./mylib") import BST #Create BST input = [3,1,2,4,5] root = BST.BSTNode(input[0]) for x in range(1,len(input)): BST.insertNode(root, BST.BSTNode(input[x])) print("BST permutations for input >>", input) result = FindCombinations(root) for c in result: print(c)
def main(): # initialize a binary search tree bst1 = BST() bst1.insert(7) bst1.insert(3) bst1.insert(8) bst1.insert(5) bst1.insert(2) bst1.insert(12) # the tree is like # 7 # / \ # 3 8 # / \ / # 2 5 12 bst2 = BST() bst2.insert(3) bst2.insert(2) bst2.insert(5) # the tree is like # 3 # / \ # 2 5 bst3 = BST() bst3.insert(3) bst3.insert(1) bst3.insert(9) print "is tree2 a subtree of tree1? ", isSubtree(bst1.root, bst2.root) print "is tree3 a subtree of tree1? ", isSubtree(bst1.root, bst3.root)
from BST import * a = BST() data = [3,5,4,2,1,6] for i in data: a.insert(i) print a.getRoot() print a.getMax() print a.getSize()
def __init__(self, value, hashFunction): BST.__init__(self, value) self.hash = hashFunction self.hashedValue = self.hash(value)
next_smallest_node = self.nodes.pop() self.size -= 1 #IMPORTANT: check node right sub-tree self.fillNodes(next_smallest_node.right) return next_smallest_node.data #Time complexity:O(1) def hasNext(self): return (self.size > 0) #Create BST root = BST.BSTNode(4) BST.insert(root, BST.BSTNode(3)) BST.insert(root, BST.BSTNode(6)) BST.insert(root, BST.BSTNode(2)) BST.insert(root, BST.BSTNode(5)) BST.insert(root, BST.BSTNode(7)) print("In order traversal >>") BinaryTreeTraversal.inOrder(root) print("") bstI = BSTIterator(root) while bstI.hasNext(): print("next smallest >>>", bstI.next())