def read_f_into_AVL(file): """Recieves glove file with embedings location as a string constructs an AVL tree using nodes with the word as one parameter and the 50 floting point vectors in an array as another. """ CurAVL = AVL.AVLTree() forAVL = open(file, 'r+', encoding="UTF-8") for line in forAVL: a = line.split() #Direguards "words" in file that do not begin witch characters from the alphabet if (a[0] >= 'A' and a[0] <= 'Z') or (a[0] >= 'a' and a[0] <= 'z'): ## did you think about using a is char() for the line above CurAVL.insert(AVL.Node(a[0], a[1:(len(a))])) return CurAVL
def InsertAVL_in_List(self,indice,dato): auxiliar=self.primero while auxiliar!=None: if auxiliar.indice==indice: if auxiliar.AVL==None: ar=AVL.Arbol() auxiliar.AVL=AVL.NodoArbol(dato) #ar.PosOrden(auxiliar.AVL) else: ar=AVL.Arbol() ar.InsertarAVL(auxiliar.AVL,dato) ar.PosOrden(auxiliar.AVL) if auxiliar.AVL.factor==2: if auxiliar.AVL.izquierdo.factor==1: n=auxiliar n1=auxiliar.AVL n2=auxiliar.AVL.izquierdo n1.izquierdo=n2.derecho n2.derecho=n1 n.AVL=n2 elif auxiliar.AVL.izquierdo.factor==-1: p=auxiliar n=auxiliar.AVL n1=auxiliar.AVL.izquierdo n2=auxiliar.AVL.izquierdo.derecho n1.derecho=n2.izquierdo n2.izquierdo=n1 n.izquierdo=n2.derecho n2.derecho=n p.AVL=n2 elif auxiliar.AVL.factor==-2: if auxiliar.AVL.derecho.factor==-1: p=auxiliar n=auxiliar.AVL n1=auxiliar.AVL.derecho n.derecho=n1.izquierdo n1.izquierdo=n p.AVL=n1 elif auxiliar.AVL.derecho.factor==1: p=auxiliar n=auxiliar.AVL n1=auxiliar.AVL.derecho n2=auxiliar.AVL.derecho.izquierdo n1.izquierdo=n2.derecho n2.derecho=n1 n.derecho=n2.izquierdo n2.izquierdo=n p.AVL=n2 auxiliar=auxiliar.siguiente
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 test_languages(fname): data = open(fname, 'r') print("Testing tree building") languages = AVL.Languages() data_by_year = languages.build_trees_from_file(data) data.close() query = 'Yiddish' data_by_name = languages.query_by_name(query) print("The statistics for English in Canada, by year:") print(data_by_name) threshold = 12973810-1 data_by_count = languages.query_by_count(threshold) print("The statistics for English in Canada, by year:") print(data_by_count) #data_by_year[1931].printout() print(data_by_year[1931].is_balanced()) return data_by_year
def create_AVL_tree(words_file): english_words = AVL.avltree() lineList = [line.rstrip('\n') for line in open(words_file)] for word in lineList: english_words.insert(word.lower()) return english_words
def create_tree(tree, fileName, userTreeOption): with open(fileName, "r") as file: for i in file: line = i.split() line[0] = line[0].lower() if (userTreeOption == 1): tree.insert(AVL.Node(line[0])) # inserts to AVL tree else: tree.insert(line[0]) # inserts to Red-Black tree
def BuscarArbol(self,indice): auxiliar=self.primero while auxiliar!=None: if auxiliar.indice==indice: if auxiliar.AVL!=None: ar=AVL.Arbol() texto=ar.GraficarArbol(auxiliar.AVL) auxiliar=auxiliar.siguiente return texto
def main(): count = [1] count[0] = 0 userWord = input("Enter a word to find anagrams for: ") userWord = userWord.lower() print( "The word", userWord.upper(), "uses two different trees to populate the dictionary.\nWhich of the two trees would you like to use?" ) while True: userTreeOption = int( input("1: AVL Tree\n2: Red-black Tree\nOption selected: ")) if (userTreeOption == 1 or userTreeOption == 2): break else: print( "I'm sorry that is not a valid answer please choose between 1 and 2\n" ) while True: fileName = input( "Enter the name of your file you wish to use to populate the dictionary: " ) try: if (userTreeOption == 1): tree = AVL.AVLTree() # creates AVL tree else: tree = RedBlack.RedBlackTree() # creates Red-Black tree create_tree(tree, fileName, userTreeOption) # opens file for tree option given break # set to true to exit loop except FileNotFoundError: print("I'm sorry that file is not found. Please try again.") print("\n---------------------------------\nThe anagrams for", userWord.upper(), "are:") print_anagrams(userWord, "", tree) count_anagrams(userWord, "", tree, count) print( "\n---------------------------------\n", userWord.upper(), "has a total of", count[0], "anagrams from the dictionary created\n---------------------------------" ) while True: fileName2 = input("Enter the name of your next file: ") try: max_anagrams( tree, count, fileName2 ) #reads second file and find the word with the most anagrams break # set to true to exit loop except FileNotFoundError: print("I'm sorry that file is not found. Please try again.")
class PatientBank(object): __procedureManager = None __patientTree = None __ID = None def __init__(self): self.__patientTree = AVL() self.__procedureManager = ProceduresManager() self.__ID = 1 def registerPatient(self, name, birth, weight, sex, gender, bloodType): patient = Patient(name, birth, weight, sex, gender, bloodType, self.__ID) self.__ID += 1 self.__patientTree.insert(patient) return str(patient.getId()) def getInfoPatient(self, patientId, attribute): patient = self.searchPatient(patientId) return patient.getInfo(attribute) def searchPatient(self, patientId): patient = self.__patientTree.search(patientId).getData() if (type(patient) == type(None)): raise PatientException("Invalid Patient ID") return patient def performProcedure(self, patientId, doctorName, procedureName, drugsCost=0, organ=None): patient = self.searchPatient(patientId) totalCost = self.__procedureManager.performProcedure( procedureName, patient, doctorName, organ) + drugsCost patient.storeSpending(totalCost) patient.changeCardType() def getMedicalRecords(self, patientId): return self.searchPatient(patientId).getMedicalRecords().__str__()
def create_index(index_name, table_name, param): table = 'BD/' + table_name + '.dbf' archivo = open(table, 'r') lineas = archivo.readlines() t = AVL() aux = 0 aux2 = 0 cabecera = lineas[aux] flag = 0 while cabecera != '------\n': datos = cabecera.split() aux2 += 1 if datos[0] == param: aux = aux2 - 1 if datos[1] == 'int': flag = 1 else: flag = 0 cabecera = lineas[aux2] contLinea = 0 for linea in lineas: if contLinea <= aux2: archivo.readline() else: arrLinea = linea.split() if flag == 1: t.insert(int(arrLinea[aux]), contLinea + 1) else: t.insert(arrLinea[aux], contLinea + 1) # print("elemento insertado", arrLinea[aux]) # print("the lines is: ",contLinea) contLinea += 1 print("arbol creado!") # t.preShow(t.root) sys.setrecursionlimit(50000) afile = open(index_name + '.pkl', 'wb') pickle.dump(t, afile) afile.close() print("\n")
import AVL tree = AVL.Tree() tree.add(15) tree.add(5) tree.add(18) tree.add(1) tree.add(9) tree.add(16) tree.add(19) tree.add(8) tree.print() tree.remove(15) tree.print() tree.add(2) tree.add(3) tree.add(4) tree.add(20) tree.add(21) tree.print() tree.add(23) tree.add(24) tree.add(25) tree.add(26) tree.add(27) tree.add(28) tree.add(29) tree.add(30) tree.add(31)
from AVL import * a = AVL(3) a.insert(AVL(1)) a.insert(AVL(5)) a.insert(AVL(4)) a.display() print("root depth is: ", a.depth()) print("root balance is: ", a.balance()) a = a.adjust() # this is the new addition a.display() print("root depth is: ", a.depth()) print("root balance is: ", a.balance()) # 3_ # / \ # 1 5 # / # 4 # root depth is: 3 # root balance is: -1 # 4_ # / \ # 2 6 # / # 5 # root depth is: 3 # root balance is: -1
root.text = str(first_elem.data) q = queue.Queue() parent = root q.put([parent, first_elem]) while not q.empty(): parent, curr_node = q.get() if curr_node: print("Curr node data: {}".format(curr_node.data)) if curr_node.left is not None: print("Curr left data: {}".format(curr_node.left.data)) child_left = etree.SubElement(parent, "left_child") child_left.text = str(curr_node.left.data) q.put([child_left, curr_node.left]) if curr_node.right is not None: print("Curr right data: {}".format(curr_node.right.data)) child_right = etree.SubElement(parent, "right_child") child_right.text = str(curr_node.right.data) q.put([child_right, curr_node.right]) tree = etree.ElementTree(root) tree.write(name, pretty_print=True) if __name__ == '__main__': elements_to_insert = [i for i in range(10)] avl = AVL.AVLTree() root = AVL.create_tree(elements_to_insert) generate_tree('xml/AVL_Tree.xml', root)
def __init__(self): self.__patientTree = AVL() self.__procedureManager = ProceduresManager() self.__ID = 1
from AVL import * nums = [10, 1, 9, 2, 8, 3, 7, 4, 6, 5] a = AVL(nums[0]) print("-------------starting with", nums[0]) a.display() for num in nums[1:]: print("-------------after we add", num) a.insert(AVL(num)) a = a.adjust() a.display() # ======== RESTART: C:\Users\dgerman\Desktop\march-08-lecture\tests-AVL.py ======== # # -------------starting with 10 # 10 # -------------after we add 1 # 10 # / # 1 # -------------after we add 9 # 9_ # / \ # 1 10 # -------------after we add 2 # _9_ # / \ # 1 10 # \ # 2 # -------------after we add 8
import argparse import AVL import BST BSTtestTree = BST.binary_search_tree() AVLtestTree = AVL.AVLTree() def readFile(fileName): countA = 0 countB = 0 try: fileObject = open(fileName, "r") for line in fileObject: line = line.lower() countA = BSTtestTree.insert(line) countB = AVLtestTree.insert(line) print("THIS IS BST") BSTtestTree.height() print("Total Duplicates: ", BSTtestTree._getDups()) print("Total Inserted: ", countA) print("THIS IS AVL") print("Height of AVL tree is: ", AVLtestTree.height()) print("Total Duplicates: ", AVLtestTree._getDups()) print("Total Inserted: ", countB)