def start_bulk_creation(n): #global bank.acc_f_n, bank.bank_f_n """ n = number of accounts to be created. returns total number of disk accesses taken to insert the n elements. """ #sys.stdout = open('data/acc_creation.log','at',encoding='utf-8') with btree.BTree(bank.bank_f_n) as my_bt, shelve.open( bank.acc_f_n, writeback=True) as ad_sf, open( bank.acc_create_log_f_n, 'at', encoding='utf-8') as acc_create_log_f: try: no_of_accounts = ad_sf['no_of_accounts'] except KeyError: ad_sf['no_of_accounts'] = 0 no_of_accounts = 0 i = 0 d_a_c = 0 while i < n: i += 1 my_acc = generate_random_account() acc_create_log_f.write(my_acc.acc_no + ' ' + my_acc.holder_name + '\n') ad_sf[str(no_of_accounts + i)] = my_acc ad_sf['no_of_accounts'] = no_of_accounts + i d_a_c += my_bt.insert_key(my_acc.acc_no, str(no_of_accounts + i)) return d_a_c
def FillBTree(): L = [6, 3, 16, 11, 7, 17, 14, 8, 5, 19, 15, 1, 2, 4, 18, 13, 9, 20, 10, 12, 21, 22] T = bt.BTree() for i in L: bt.Insert(T,i) return T
def evaluate_dense_distribution(self, distribution): self.btree = bt.BTree(self.degree) self._load_dense_data(distribution) print("Building") startTime = time.time() self.btree.build(self.keys, self.values) endTime = time.time() buildTime = endTime - startTime print("Build BTree Time: " + str(buildTime)) print("Predicting") cost = 0 startTime = time.time() for key in self.keys: searchResult = self.btree.search(bt.Item(key, -1)) if not searchResult["found"]: print("Should never happen!") assert (1 == 0) cost += searchResult["itemCount"] endTime = time.time() averageSearchTime = (endTime - startTime) / len(self.keys) averageCost = cost / len(self.keys) print("Average search time: " + str(averageSearchTime)) print("Average cost: " + str(averageCost)) self._dump_result(distribution, buildTime, averageSearchTime, averageCost)
def buildBTree(max, filename): # set the max value of b tree to the value passed as max parameter T = btree.BTree([], max_data=max) f = open(filename, "r", encoding="utf8") for line in f: # tokenize each line into a list of strings tokens = line.split(" ") # if the value stored at the index begins with an alphabetical letter if tokens[0].isalpha(): btree.Insert(T, WordEmbedding(tokens[0], tokens[1:])) f.close() # close the file to save memory return T # return btree
def List_it(self, data, value): frame = tk.Toplevel(self) #Imprime o dado selecionado, tal como o usuario o digitou label = tk.Label(frame, text="%s" % (data)) label.pack() #Seta scrollbar e text box S = tk.Scrollbar(frame) T = tk.Text(frame, height=10, width=50) S.pack(pady=2, padx=2, side=RIGHT) T.pack(pady=2, padx=2, side=LEFT) S.config(command=T.yview) T.config(yscrollcommand=S.set) #Padroniza a entrada data = unidecode(data) data = data.lower() data = data.split(' ') data = ''.join(data) lista = [] #Inicializa a arvore B b = btree.BTree(4) nameoffile = "../data/Btrees/" + data + ".pkl" if not os.path.exists(nameoffile): T.insert(CURRENT, "There is no such data.\n") else: file = open(nameoffile, 'rb') b = pickle.load(file) file.close() #Estamos usando apenas a arvore B, uma vez que teriamos problemas com o Pickle #Teriamos que abrir e fechar o arquivo a cada pesquisa, pois ele eh um serializador if value == 0: lista = b.crescent(b._root, lista) else: lista = b.decrescent(b._root, lista) #For que imprime cada objeto da lista organizada for obj in lista: if obj[0] != 0: T.insert(CURRENT, obj[1] + ' \t\t ' + str(obj[0]) + "\n") else: T.insert(CURRENT, obj[1] + ' \t\t ' + 'n.a.' + "\n")
def readIntoBTree(max): tree = btree.BTree([], max_data=max) with open(embed_file, encoding="utf8") as ef: content = ef.readline() #goes through every line on the file while content: word = content.split() #creates Word Embedding with information from file n = WordEmbedding.WordEmbedding(word[0], word[1:]) #inserts on btree btree.Insert(tree, n) btree.Print content = ef.readline() print("Done") return tree
def create_single_account(my_acc): """ returns the number of disk accesses taken for account creation """ #global bank.acc_f_n, bank.bank_f_n with btree.BTree(bank.bank_f_n) as my_bt, shelve.open( bank.acc_f_n, writeback=True) as ad_sf, open( bank.acc_create_log_f_n, 'at', encoding='utf-8') as acc_create_log_f: try: no_of_accounts = ad_sf['no_of_accounts'] except KeyError: ad_sf['no_of_accounts'] = 0 no_of_accounts = 0 my_acc = generate_random_account() acc_create_log_f.write(my_acc.acc_no + ' ' + my_acc.holder_name + '\n') ad_sf[str(no_of_accounts + 1)] = my_acc ad_sf['no_of_accounts'] = no_of_accounts + 1 return my_bt.insert_key(my_acc.acc_no, str(no_of_accounts + 1))
def Display(self, country): frame = tk.Toplevel(self) #Exibe o nome do pais, assim como o usuário o digitou label = tk.Label(frame, text="%s" % (country)) label.grid(row=0, column=2) #Seta scrollbar e text box S = tk.Scrollbar(frame) T = tk.Text(frame, height=10, width=50) S.grid(pady=2, padx=2, row=2, column=0) T.grid(pady=2, padx=2, row=2, column=1, columnspan=3) S.config(command=T.yview) T.config(yscrollcommand=S.set) #Para pastas irmas, usar o '../' antes de Btrees bname = open("../data/Btrees/names.pkl", 'rb') #Inicializa e desserializa a arvore B b = btree.BTree(4) b = pickle.load(bname) nodo = b.show([country]) index = nodo[ 1] #Recebe o indice (usado como ponteiro) para o arquivo binario bname.close() binary = open("../data/Btrees/binaries.kbb", 'rb') for num in range(0, index): count = pickle.load(binary) #Recebe o pais de indice 'index' binary.close() #Seta path para mapa e bandeira mapa = count.return_path_map() flag = count.return_path_flag() #Bandeira do pais #Cria imagem temporaria reduzida im_temp = Image.open(flag) im_temp = im_temp.resize((175, 90), Image.ANTIALIAS) im_temp.save("teste.gif", "gif") flag = tk.PhotoImage(file="teste.gif") painel11 = tk.Label(frame, image=flag) painel11.image = flag painel11.grid(row=1, column=1) #Mapa do pais im_temp = Image.open(mapa) im_temp = im_temp.resize((175, 90), Image.ANTIALIAS) im_temp.save("teste.gif", "gif") mapa = tk.PhotoImage(file="teste.gif") painel1 = tk.Label(frame, image=mapa) painel1.image = mapa painel1.grid(row=1, column=3) #Exibicao do objeto Pais selecionado (modo naive) T.insert(CURRENT, "Capital:\t\t" + count.capital + '\n') T.insert(CURRENT, "ISO3166a2:\t\t" + count.iso3166a2 + '\n') T.insert(CURRENT, "ISO3166a3:\t\t" + count.iso3166a3 + '\n') T.insert(CURRENT, "Internet TLD:\t\t" + count.internetTLD + '\n') T.insert(CURRENT, "Calling Code:\t\t" + count.callingCode + '\n') T.insert(CURRENT, "Continent:\t\t" + count.continent + '\n') T.insert(CURRENT, "Government:\t\t" + count.government + '\n') T.insert(CURRENT, "Population:\t\t" + str(count.population) + '\n') T.insert(CURRENT, "Area:\t\t" + str(count.area) + '\n') T.insert(CURRENT, "Coast Area:\t\t" + str(count.coastArea) + '\n') T.insert(CURRENT, "HDI:\t\t" + str(count.hdi) + '\n') T.insert(CURRENT, "GINI:\t\t" + str(count.gini) + '\n') T.insert(CURRENT, "Life Expec.:\t\t" + str(count.lifeExp) + '\n') T.insert(CURRENT, "Currency:\t\t" + count.currencyName + '\n') T.insert(CURRENT, "Currency 3 L.:\t\t" + count.currency3letter + '\n') T.insert(CURRENT, "GDP:\t\t" + str(count.gdp) + '\n') T.insert(CURRENT, "Inflation:\t\t" + str(count.inflation) + '\n') T.insert(CURRENT, "Tourism:\t\t" + str(count.tourism) + '\n') T.insert(CURRENT, "Currency Exch.:\t\t" + str(count.currencyExchange) + '\n')
import objPais import pickle import btree as b btree = b.BTree(4) binaries = open('binaries.kbb', 'rb') arq = open('tourism.pkl', 'wb') for i in range(1, 196): pais = pickle.load(binaries) print(pais.name) btree.insert([pais.tourism, pais.name, i]) pickle.dump(btree, arq) binaries.close() arq.close()
def note(self): ''' Summary ==== Print chapter18.2 note Example ==== ```python Chapter18_2().note() ``` ''' print('chapter18.2 note as follow') print('18.2 对B树的基本操作') print('这一节给出操作B-TREE-SEARCH, B-TREE-CREATE和B-TREE-INSERT的细节,两个约定:') print(' (1) B树的根结点始终在主存中,因而无需对根做DISK-DEAD;但是,', '每当根结点被改变后,都需要对根结点做一次DISK-WRITE') print(' (2) 任何被当做参数的结点被传递之前,要先对它们做一次DISK-READ') print('给出的过程都是\"单向\"算法,即它们沿树的根下降,没有任何回溯') print('搜索B树') print(' 搜索B树有搜索二叉查找树很相似,只是不同于二叉查找树的两路分支,而是多路分支') print(' 即在每个内结点x处,要做x.n+1路的分支决定') print(' B-TREE-SEARCH是定义在二叉查找树上的TREE-SEARCH过程的一个直接推广。', '它的输入是一个指向某子树的根结点x的指针,以及要在该子树中搜索的一个关键字k', '顶层调用的形式为B-TREE-SEARCH(root, key).如果k在B树中,', 'B-TREE-SEARCH就返回一个由结点y和使keyi[y]==k成立的下标i组成的有序对(y, i)', '否则返回NONE') print(' 像在二叉查找树的TREE-SEARCH过程中那样,在递归过程中所遇到的结点构成以一条从树根下降的路径') print('创建一棵空的B树') print(' 为构造一棵B树T,先用B-TREE-CREATE来创建一个空的根结点,再调用B-TREE-INSERT来加入新的关键字') print('向B树插入关键字') print(' 与向二叉查找树中插入一个关键字相比向B树中插入一个关键字复杂得多。') print(' 像在二叉查找树中一样,要查找插入新关键字的叶子位置。', '但是在B树中,不能简单地创建一个新的叶结点,然后将其插入,因为这样得到的树不再是一颗有效的B树') print('B树中结点的分裂') print(' 过程B-TREE-SPLIT-CHILD的输入一个非满的内结点x(假定在主存当中)', '下标i以及一个结点y(同样假定在其主存当中),y=x.c[i]是x的一个满子结点') print(' 该过程把这个孩子分裂两个,并调整x使之有一个新增的孩子') print(' 要分裂一个满的根,首先让根成为一个新的空跟结点的孩子,', '这样才能够使用B-TREE-SPLIT-CHILD,树的高度因此增加1,分裂是树长高的唯一途径') print('对B树用单程下行便利树方式插入关键字') print( '对一棵高度为h的B树,B-TREE-INSERT要做的磁盘存取次数为O(h),因为在调用B-TREE-INSERT-NONFULL之间', '只做了O(1)次DISK-READ和DISK-WRITE操作,所占用的总的CPU时间为O(th)=O(tlogt(n))') print('因为B-TREE-INSERT-NONFULL是尾递归的,故也可以用一个while循环来实现') print('说明了在任何时刻,需要留在主存中的页面数为O(1)') keys = ['F', 'S', 'Q', 'K', 'C', 'L', 'H', 'T', 'V', \ 'W', 'M', 'R', 'N', 'P', 'A', 'B', 'X', 'Y', 'D', 'Z', 'E'] btree = bt.BTree(2) for key in keys: btree.insert(key) print('练习18.2-1 请给出关键字', keys, '依照顺序插入一棵最小度数为2的空的B树的结果') print(btree.root) print('练习18.2-2 在child_split的情况下,在调用B-TREE-INSERT的过程中', '会执行冗余的DISK-READ或DISK-WRITE') print(' 所谓冗余的DISK-READ是指') print('练习18.2-3 前驱从最大子结点的最大关键字寻找,后继从最小自结点的最小关键字寻找') print('练习18.2-4 假设关键字{1,2,...,n}被插入一个最小度数为2的空B树中。最终的B树有多少结点') btree = bt.BTree(2) for i in range(1, 12): btree.insert(i) print(btree.root) btree.display() print(' 由于每次插入的树的关键字都比前面的字大,因此新关键字永远是放到了最右边的结点中') print(' 除了最右边一直往下的路径上的结点(记为R)中的关键字数有可能大于1外') print(' 其他所有节点的关键字数量都是1,当所有的R结点都有三个关键字时,有最少的结点数') print(' 此时n=2^(h+1)-1+2(h+1),其中h是B树的高度,结点数2^(h+1)-1.') print(' 而2^(h+1)-1=n-2(h+1),其中h=Θ(lgn),因此结点数为Θ(n)') print('练习18.2-5 因为叶子结点无需指向子女的指针,对同样大小的磁盘页') print(' 可选用一个与内结点不同的(更大的)t值') print('练习18.2-6 假设B-TREE-SEARCH的实现是在每个结点处采用二叉查找,而不是线性查找。') print(' 证明无论怎样选择t(t为n的函数)。这种实现所需的CPU时间都为O(lgn)') print('练习18.2-7 假设磁盘硬件允许任意选择磁盘页的大小,但读取磁盘页的时间为a+bt') print(' 其中a和b为规定的常数,t为确定磁盘页的大小后,B树的最小度数') print(' 请描述如何选择t以最小化B树的查找时间。对a=5毫秒和b=10微秒,请给出t的一个最优值')
if k in t.data: for d in t.data: print(d, end=' ') print() else: if not t.is_leaf: i = 0 while i < len(t.data) and k > t.data[i]: i += 1 printItemsInNode(t.child[i], k) if __name__ == "__main__": plt.close('all') T = btree.BTree() nums = [ 6, 3, 23, 16, 11, 25, 7, 17, 27, 30, 21, 14, 26, 8, 29, 22, 28, 5, 19, 24, 15, 1, 2, 4, 18, 13, 9, 20, 10, 12 ] t = T.find(4) for num in nums: T.insert(num) T2 = btree.BTree() for num in [32, 12, 58, 7, 43]: T2.insert(num) T.draw()
print('Question 1') TA.inOrder() decrease_min(TA) TA.inOrder() TA.draw() TB.inOrder() decrease_min(TB) TB.inOrder() TB.draw() print('Question 2') nums = [6, 3, 23,16, 11, 25, 7,21, 14, 26, 8, 29, 22, 28, 5, 19, 24, 15, 1, 2, 4, 18, 13, 9, 20, 10, 12] T = btree.BTree() for num in nums: T.insert(num) T.draw() print_data(T) increase_max(T) T.draw() print_data(T) print('Question 3') L = [2,4,6,11,13,3,1,12] H = htc.HashTableChain(9) for i in L: H.insert(i)
import random import btree if __name__ == "__main__": rand_list = [random.randrange(1, 10) for _ in range(150)] # rand_list = [i for i in range(10)] # rand_list.reverse() tree = btree.BTree(3) for key in rand_list: tree.insert(key) tree.display() print(f"Узел и позиция (от нуля): {tree.search(2)}")
def main(): points = 23 try: print("**** BTree of degree 2 created.") tree = btree.BTree(2) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,0,[None, None, None, None],[None, None, None, None, None],1) },1,2)""": print("**** Passed that test\n") points += 1 else: print("*** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 5") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 0, [None, None, None, None], [None, None, None, None, None], 1) }, 1, 2) tree.insert(5) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,1,[5, None, None, None],[None, None, None, None, None],1) },1,2)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 3") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 1, [5, None, None, None], [None, None, None, None, None], 1) }, 1, 2) tree.insert(3) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[3, 5, None, None],[None, None, None, None, None],1) },1,2)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 10") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [3, 5, None, None], [None, None, None, None, None], 1) }, 1, 2) tree.insert(10) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,3,[3, 5, 10, None],[None, None, None, None, None],1) },1,2)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 1") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 3, [3, 5, 10, None], [None, None, None, None, None], 1) }, 1, 2) tree.insert(1) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,4,[1, 3, 5, 10],[None, None, None, None, None],1) },1,2)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 15 causing a split") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 4, [1, 3, 5, 10], [None, None, None, None, None], 1) }, 1, 2) tree.insert(15) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[1, 3, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,2,[10, 15, None, None],[None, None, None, None, None],2) , 3: BTreeNode(2,1,[5, None, None, None],[1, 2, None, None, None],3) },3,4)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 25") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [1, 3, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 2, [10, 15, None, None], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 1, [5, None, None, None], [1, 2, None, None, None], 3) }, 3, 4) tree.insert(25) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[1, 3, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,3,[10, 15, 25, None],[None, None, None, None, None],2) , 3: BTreeNode(2,1,[5, None, None, None],[1, 2, None, None, None],3) },3,4)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 21") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [1, 3, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 3, [10, 15, 25, None], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 1, [5, None, None, None], [1, 2, None, None, None], 3) }, 3, 4) tree.insert(21) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[1, 3, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,4,[10, 15, 21, 25],[None, None, None, None, None],2) , 3: BTreeNode(2,1,[5, None, None, None],[1, 2, None, None, None],3) },3,4)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 23 causing a split") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [1, 3, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 4, [10, 15, 21, 25], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 1, [5, None, None, None], [1, 2, None, None, None], 3) }, 3, 4) tree.insert(23) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[1, 3, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,2,[10, 15, None, None],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[5, 21, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,2,[23, 25, None, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 17") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [1, 3, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 2, [10, 15, None, None], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 2, [5, 21, None, None], [1, 2, 4, None, None], 3), 4: btree.BTreeNode(2, 2, [23, 25, None, None], [None, None, None, None, None], 4) }, 3, 5) tree.insert(17) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[1, 3, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,3,[10, 15, 17, None],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[5, 21, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,2,[23, 25, None, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 19") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [1, 3, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 3, [10, 15, 17, None], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 2, [5, 21, None, None], [1, 2, 4, None, None], 3), 4: btree.BTreeNode(2, 2, [23, 25, None, None], [None, None, None, None, None], 4) }, 3, 5) tree.insert(19) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[1, 3, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,4,[10, 15, 17, 19],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[5, 21, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,2,[23, 25, None, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Deleting 1 causing redistribute from the right.") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [1, 3, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 4, [10, 15, 17, 19], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 2, [5, 21, None, None], [1, 2, 4, None, None], 3), 4: btree.BTreeNode(2, 2, [23, 25, None, None], [None, None, None, None, None], 4) }, 3, 5) tree.delete(1) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[3, 5, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,3,[15, 17, 19, None],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[10, 21, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,2,[23, 25, None, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 20") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [3, 5, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 3, [15, 17, 19, None], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 2, [10, 21, None, None], [1, 2, 4, None, None], 3), 4: btree.BTreeNode(2, 2, [23, 25, None, None], [None, None, None, None, None], 4) }, 3, 5) tree.insert(20) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[3, 5, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,4,[15, 17, 19, 20],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[10, 21, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,2,[23, 25, None, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Deleting 23 causing redistribute from the left.") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [3, 5, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 4, [15, 17, 19, 20], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 2, [10, 21, None, None], [1, 2, 4, None, None], 3), 4: btree.BTreeNode(2, 2, [23, 25, None, None], [None, None, None, None, None], 4) }, 3, 5) tree.delete(23) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[3, 5, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,3,[15, 17, 19, None],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[10, 20, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,2,[21, 25, None, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Inserting 24") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [3, 5, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 3, [15, 17, 19, None], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 2, [10, 20, None, None], [1, 2, 4, None, None], 3), 4: btree.BTreeNode(2, 2, [21, 25, None, None], [None, None, None, None, None], 4) }, 3, 5) tree.insert(24) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[3, 5, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,3,[15, 17, 19, None],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[10, 20, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,3,[21, 24, 25, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") print("\n**** Deleting 20 from interior node.") tree.delete(20) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[3, 5, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,3,[15, 17, 19, None],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[10, 21, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,2,[24, 25, None, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() try: print("\n**** Deleting 21") tree = btree.BTree( 2, { 1: btree.BTreeNode(2, 2, [3, 5, None, None], [None, None, None, None, None], 1), 2: btree.BTreeNode(2, 3, [15, 17, 19, None], [None, None, None, None, None], 2), 3: btree.BTreeNode(2, 2, [10, 21, None, None], [1, 2, 4, None, None], 3), 4: btree.BTreeNode(2, 2, [24, 25, None, None], [None, None, None, None, None], 4) }, 3, 5) tree.delete(21) print(repr(tree)) if repr(tree) == """BTree(2, {1: BTreeNode(2,2,[3, 5, None, None],[None, None, None, None, None],1) , 2: BTreeNode(2,2,[15, 17, None, None],[None, None, None, None, None],2) , 3: BTreeNode(2,2,[10, 19, None, None],[1, 2, 4, None, None],3) , 4: BTreeNode(2,2,[24, 25, None, None],[None, None, None, None, None],4) },3,5)""": print("**** Passed that test\n") points += 1 else: print("**** There was a problem\n") except Exception as ex: print("**** There was an exception while running your code.") print(ex) print() print("*** You got", points, "out of 40 points for the program.")
def printItemsInNode(t, k): if type(t) == btree.BTree: t = t.root if k in t.data: print(*t.data, end=' ') if not t.is_leaf: for i in t.child: printItemsInNode(i, k) if __name__ == "__main__": plt.close('all') T = btree.BTree() nums = [ 6, 3, 23, 16, 11, 25, 7, 17, 27, 30, 21, 14, 26, 8, 29, 22, 28, 5, 19, 24, 15, 1, 2, 4, 18, 13, 9, 20, 10, 12 ] t = T.find(4) for num in nums: T.insert(num) T2 = btree.BTree() for num in [32, 12, 58, 7, 43]: T2.insert(num) T_empty = btree.BTree()
def __init__(self): self.timed = btree.BTree(TIMED_BRANCHING_ORDER) self.zero_timeout = set() self.paused = set()
T = T.root if T.child[0].is_leaf: T.is_leaf = True else: for item in T.child: prune_leaves(item) return T # problme of type 2 must traverse the whole tree def make_binary(T): return if __name__ == "__main__": plt.close('all') T = btree.BTree() T2 = btree.BTree() T3 = btree.BTree() nums = [6, 3, 16, 11, 7, 17, 14, 8, 5, 19, 15, 1, 2, 4, 18, 13, 9, 20, 10, 12, 21] for num in nums: T.insert(num) T3.insert(num) T3.insert(num+21) T.draw('Original tree') for i in range(5): T2.insert(i) T2.draw('One-node tree') T3.draw('Bigger tree') print('Question 1') print(roots_children(T)) # [3, 7, 14, 17]
def Compare(self, country1, country2): frame = tk.Toplevel(self) #Adicione '../' antes de Btrees, se esta numa pasta irma bname = open("../data/Btrees/names.pkl", 'rb') b = btree.BTree(4) b = pickle.load(bname) nodo = b.show([country1]) ind1 = nodo[1] nodo = b.show([country2]) ind2 = nodo[1] bname.close() #Como usamos um serializador, eh necessario verificar qual tem o menor indice. #Se isso nao for feito, ocorre um erro. if ind1 > ind2: aux = country1 country1 = country2 country2 = aux a = ind1 ind1 = ind2 ind2 = a #Exibe a string "#pais1 vs #pais2" label1 = tk.Label(frame, text="%s" % (country1), font=LARGE_FONT) label1.grid(row=0, column=2, sticky="E") labelvs = tk.Label(frame, text="vs", font=LARGE_FONT) labelvs.grid(row=0, column=3) label2 = tk.Label(frame, text="%s" % (country2), font=LARGE_FONT) label2.grid(row=0, column=4, sticky="W") #Adicione '../' antes de Btrees, se esta numa pasta irma binary = open("../data/Btrees/binaries.kbb", 'rb') for num in range( 0, ind1): #Busca, com base no indice, o bloco do pais solicitado count1 = pickle.load(binary) for num in range(0, ind2 - ind1): count2 = pickle.load(binary) binary.close() #Seta o path para os mapas e bandeiras map1 = count1.return_path_map() map2 = count2.return_path_map() flag1 = count1.return_path_flag() flag2 = count2.return_path_flag() #Bandeira do pais 1 #As primeiras tres linhas nos 4 casos sao para o tratamento da imagem im_temp = Image.open(flag1) im_temp = im_temp.resize((175, 90), Image.ANTIALIAS) im_temp.save("teste.gif", "gif") flag1 = tk.PhotoImage(file="teste.gif") painel11 = tk.Label(frame, image=flag1) painel11.image = flag1 #mantenha a referencia, mantenha a referencia, mantenha a refere... painel11.grid(row=1, column=1) #Mapa do pais 1 im_temp = Image.open(map1) im_temp = im_temp.resize((175, 90), Image.ANTIALIAS) im_temp.save("teste.gif", "gif") map1 = tk.PhotoImage(file="teste.gif") painel1 = tk.Label(frame, image=map1) painel1.image = map1 #mantenha a referencia, mantenha a referencia, mantenha a refere... painel1.grid(row=1, column=2) #Bandeira do pais 2 im_temp = Image.open(flag2) im_temp = im_temp.resize((175, 90), Image.ANTIALIAS) im_temp.save("teste.gif", "gif") flag2 = tk.PhotoImage(file="teste.gif") painel22 = tk.Label(frame, image=flag2) painel22.image = flag2 #mantenha a referencia, mantenha a referencia, mantenha a refere... painel22.grid(row=1, column=4) #Mapa do pais 2 im_temp = Image.open(map2) im_temp = im_temp.resize((175, 90), Image.ANTIALIAS) im_temp.save("teste.gif", "gif") map2 = tk.PhotoImage(file="teste.gif") painel2 = tk.Label(frame, image=map2) painel2.image = map2 #mantenha a referencia, mantenha a referencia, mantenha a refere... painel2.grid(row=1, column=5) S1 = tk.Scrollbar(frame) T1 = tk.Text(frame, height=10, width=50) S1.grid(pady=2, padx=2, row=2, column=0) T1.grid(pady=2, padx=2, row=2, column=1, columnspan=2) S2 = tk.Scrollbar(frame) T2 = tk.Text(frame, height=10, width=50) S2.grid(pady=2, padx=2, row=2, column=6) T2.grid(pady=2, padx=2, row=2, column=4, columnspan=2) S1.config(command=T1.yview) T1.config(yscrollcommand=S1.set) S2.config(command=T2.yview) T2.config(yscrollcommand=S2.set) #Dados sao impressos de maneira ingenua (nao conseguimos desenvolver outra implementacao) T1.insert(CURRENT, "Capital:\t\t" + count1.capital + '\n') T2.insert(CURRENT, "Capital:\t\t" + count2.capital + '\n') T1.insert(CURRENT, "ISO3166a2:\t\t" + count1.iso3166a2 + '\n') T2.insert(CURRENT, "ISO3166a2:\t\t" + count2.iso3166a2 + '\n') T1.insert(CURRENT, "ISO3166a3:\t\t" + count1.iso3166a3 + '\n') T2.insert(CURRENT, "ISO3166a3:\t\t" + count2.iso3166a3 + '\n') T1.insert(CURRENT, "Internet TDL:\t\t" + count1.iso3166a2 + '\n') T2.insert(CURRENT, "Internet TDL:\t\t" + count2.iso3166a2 + '\n') T1.insert(CURRENT, "Calling Code:\t\t" + count1.iso3166a2 + '\n') T2.insert(CURRENT, "Calling Code:\t\t" + count2.iso3166a2 + '\n') T1.insert(CURRENT, "Continent:\t\t" + count1.continent + '\n') T2.insert(CURRENT, "Continent:\t\t" + count2.continent + '\n') T1.insert(CURRENT, "Government:\t\t" + count1.government + '\n') T2.insert(CURRENT, "Government:\t\t" + count2.government + '\n') T1.tag_config('destaque', font=('Courier', 9, 'bold')) T2.tag_config('destaque', font=('Courier', 9, 'bold')) if count1.population > count2.population: T1.insert(CURRENT, "Population:\t\t" + str(count1.population) + '\n', 'destaque') T2.insert(CURRENT, "Population:\t\t" + str(count2.population) + '\n') else: T1.insert(CURRENT, "Population:\t\t" + str(count1.population) + '\n') T2.insert(CURRENT, "Population:\t\t" + str(count2.population) + '\n', 'destaque') if count1.area > count2.area: T1.insert(CURRENT, "Area:\t\t" + str(count1.area) + '\n', 'destaque') T2.insert(CURRENT, "Area:\t\t" + str(count2.area) + '\n') else: T1.insert(CURRENT, "Area:\t\t" + str(count1.area) + '\n') T2.insert(CURRENT, "Area:\t\t" + str(count2.area) + '\n', 'destaque') if count1.coastArea > count2.coastArea: T1.insert(CURRENT, "Coast Area:\t\t" + str(count1.coastArea) + '\n', 'destaque') T2.insert(CURRENT, "Coast Area:\t\t" + str(count2.coastArea) + '\n') else: T1.insert(CURRENT, "Coast Area:\t\t" + str(count1.coastArea) + '\n') T2.insert(CURRENT, "Coast Area:\t\t" + str(count2.coastArea) + '\n', 'destaque') if count1.hdi > count2.hdi: T1.insert(CURRENT, "HDI:\t\t" + str(count1.hdi) + '\n', 'destaque') T2.insert(CURRENT, "HDI:\t\t" + str(count2.hdi) + '\n') else: T1.insert(CURRENT, "HDI:\t\t" + str(count1.hdi) + '\n') T2.insert(CURRENT, "HDI:\t\t" + str(count2.hdi) + '\n', 'destaque') if count1.gini < count2.gini: T1.insert(CURRENT, "GINI:\t\t" + str(count1.gini) + '\n', 'destaque') T2.insert(CURRENT, "GINI:\t\t" + str(count2.gini) + '\n') else: T1.insert(CURRENT, "GINI:\t\t" + str(count1.gini) + '\n') T2.insert(CURRENT, "GINI:\t\t" + str(count2.gini) + '\n', 'destaque') if count1.lifeExp > count2.lifeExp: T1.insert(CURRENT, "Life Expectancy:\t\t" + str(count1.lifeExp) + '\n', 'destaque') T2.insert(CURRENT, "Life Expectancy:\t\t" + str(count2.lifeExp) + '\n') else: T1.insert(CURRENT, "Life Expect.:\t\t" + str(count1.lifeExp) + '\n') T2.insert(CURRENT, "Life Expect.:\t\t" + str(count2.lifeExp) + '\n', 'destaque') T1.insert(CURRENT, "Currency:\t\t" + count1.currencyName + '\n') T2.insert(CURRENT, "Currency:\t\t" + count2.currencyName + '\n') T1.insert(CURRENT, "Currency 3 L:\t\t" + count1.currency3letter + '\n') T2.insert(CURRENT, "Currency 3 L:\t\t" + count2.currency3letter + '\n') if count1.gdp > count2.gdp: T1.insert(CURRENT, "GDP:\t\t" + str(count1.gdp) + '\n', 'destaque') T2.insert(CURRENT, "GDP:\t\t" + str(count2.gdp) + '\n') else: T1.insert(CURRENT, "GDP:\t\t" + str(count1.gdp) + '\n') T2.insert(CURRENT, "GDP:\t\t" + str(count2.gdp) + '\n', 'destaque') if count1.inflation < count2.inflation: T1.insert(CURRENT, "Inflation:\t\t" + str(count1.inflation) + '\n', 'destaque') T2.insert(CURRENT, "Inflation:\t\t" + str(count2.inflation) + '\n') else: T1.insert(CURRENT, "Inflation:\t\t" + str(count1.inflation) + '\n') T2.insert(CURRENT, "Inflation:\t\t" + str(count2.inflation) + '\n', 'destaque') if count1.tourism > count2.tourism: T1.insert(CURRENT, "Tourism:\t\t" + str(count1.tourism) + '\n', 'destaque') T2.insert(CURRENT, "Tourism:\t\t" + str(count2.tourism) + '\n') else: T1.insert(CURRENT, "Tourism:\t\t" + str(count1.tourism) + '\n') T2.insert(CURRENT, "Tourism:\t\t" + str(count2.tourism) + '\n', 'destaque') if count1.currencyExchange < count2.currencyExchange: T1.insert( CURRENT, "Currency Exch.:\t\t" + str(count1.currencyExchange) + '\n', 'destaque') T2.insert( CURRENT, "Currency Exch.:\t\t" + str(count2.currencyExchange) + '\n') else: T1.insert( CURRENT, "Currency Exch.:\t\t" + str(count1.currencyExchange) + '\n') T2.insert( CURRENT, "Currency Exch.:\t\t" + str(count2.currencyExchange) + '\n', 'destaque')
import account_create,btree from math import log from bank import bank_f_n ins_n = [0,100,200,300,400,500,600,700,800,900,1000,1500,2000,2500,3000,3500,4000,4500,5000,10000,20000,30000,40000,50000,75000,100000] if __name__ == '__main__': i = 0 with open('bulk_insert_results.csv','wt',encoding='utf-8') as r_f: for i in range(1,len(ins_n)): print('i = ',i) account_create.start_bulk_creation(ins_n[i] - ins_n[i-1] - 1) local_d_a_c = account_create.create_single_account(account_create.generate_random_account()) with btree.BTree(bank_f_n) as my_bt: h = my_bt.get_height() r_f.write(str(ins_n[i]) + ',' + str(h) + ',' + str(local_d_a_c) + ',' + str(log(ins_n[i])/log(6)) + '\n')
import bank, shelve, btree with btree.BTree('data/bank.sf') as my_bt, shelve.open( 'data/accounts_data.sf', writeback=True) as ad_sf: while True: req_acc_no = input('Enter account number: ') my_key = my_bt.get_key(req_acc_no) print('Disk accesses: ', my_key[1]) print('Tree height: ', my_bt.get_height()) print('Tree key count: ', my_bt.get_key_count()) if my_key[0] == None: print('Key does not exist!') continue data_loc = my_key[0][1] my_acc = ad_sf[data_loc] print(my_acc)