====== B-Tree ====== Nella lezione del 3/12 abbiamo introdotto i [[wp>B_Tree|B-Tree]]. **Implementazione dei B-Tree in Python** class InvalidBTreeException(Exception): pass class NonFullSplitException(Exception): pass class BTree(object): def __init__(self,parent,chld,elem,degree=2,isLeaf=True): '''Default: 2-3-4 Tree''' self.isLeaf=isLeaf self.children=chld self.keys=elem self.minkeys=degree-1 self.maxkeys=2*degree-1 self.parent=parent if parent and (len(self.keys)>self.maxkeys or len(self.keys) self.keys[i] : i+=1 self.children[i].insert(key) return self.root() def printtree(self,prefix=''): print prefix, self.keys for i in self.children : i.printtree(prefix+' ') def root(self): if self.parent==None : return self return self.parent.root() def check(self): for c in self.children : if c.parent!=self : self.printtree() raise InvalidBTreeException, "Wrong parent-child relation! on "+`self.keys`+' '+`c.keys` else : c.check() if __name__ == '__main__' : bt = BTree(None,[],[2,4]) bt=bt.insert(3) bt=bt.insert(1) bt=bt.insert(5) bt=bt.insert(9) bt=bt.insert(7) bt=bt.insert(13) bt=bt.insert(6) bt.printtree() bt.check() bt=bt.insert(11) bt.printtree() bt.check() bt=bt.insert(10) {{teaching:info3:btree.tgz|Qui}} trovate il codice relativo.