def main(): tree = Tree() k = eval(input('输入k的值:')) num_li = [5, 3, 7, 2, 4, 6, 8] for i in num_li: tree.add(i) tree.inner_travel(tree.root) print(kth_node(tree.root, k))
def test_create_tree_with_add(self): tree = Tree(4, 50) tree.add(25) tree.add(75) tree.add(37) tree.add(31) tree.add(43) tree.add(62) tree.add(55) tree.add(84) tree.add(92) self.assertEqual(self.result_data, tree.data)
def minmax(self, grid: Grid, depth: int, player: Player) -> int: """ """ current_tree = Tree() if grid.is_finished() or depth == 0: #print(grid, "val :", self.eval(grid, depth), "player",player) value = self.eval(grid, depth) current_tree.set_value(value) #grid.cancel_move() return value, current_tree empty_square = grid.get_empty_square() if player.color == self.color: value = [] for available_pos in empty_square: grid.add_a_pawn(self, available_pos[0], available_pos[1]) current_value, branch = self.minmax(grid, depth - 1, player.adversary) branch.set_pos(available_pos) current_tree.add(branch) value.append(current_value) grid.cancel_move() value = max(value) current_tree.set_value(value) return value, current_tree else: value = [] for available_pos in empty_square: grid.add_a_pawn(self.adversary, available_pos[0], available_pos[1]) current_value, branch = self.minmax(grid, depth - 1, player.adversary) branch.set_pos(available_pos) current_tree.add(branch) value.append(current_value) grid.cancel_move() value = min(value) current_tree.set_value(value) return value, current_tree
def test_tree(self): tree = Tree() tree.add(3) tree.add(4) tree.add(0) tree.add(8) tree.add(2) tree.print_tree() assert True
def createTree(depth, memoryLength): funcNodes = ['AND', 'OR', 'NOT', 'XOR'] agents = ['P', 'O'] tree_list = [] # Initialize a tree tree = Tree() if depth == 1: # Obtain the two things needed to make a leaf agent = random.choice(agents) num = random.randrange(1, (memoryLength + 1)) # The termination node created leaf = agent + str(num) # Set the value equal to the created leaf tree.add(leaf) tree_list.append(leaf) else: for level in range(depth): if level == 0: value = random.choice(funcNodes) tree.add(value) tree_list.append(value) elif level is not (depth - 1): for node in range(2**level): value = random.choice(funcNodes) tree.add(value) tree_list.append(value) else: for node in range(2**level): agent = random.choice(agents) num = random.randrange(1, (memoryLength + 1)) leaf = agent + str(num) tree.add(leaf) tree_list.append(leaf) return tree, tree_list
class C45: folder = 'Data/temp/' def __init__(self, file): util.cleanTempFolder(self.folder) self.tree = Tree() reader = pd.read_excel(file, header=0) self.total_instances = len(reader._get_values) self.result = self.main(file, None) def shouldStop(self, attribute_summarize, columns): if columns == 1 or attribute_summarize[-1][ 'total_disctint_values'] == 1: return True for i in range(len(attribute_summarize) - 1): if attribute_summarize[i]['total_disctint_values'] > 1: return False return True def obtainTagIndex(self, tags): tagCounter = float('-inf') tagIndex = -1 for ind in range(len(tags)): if tags[ind]['count'] > tagCounter: tagCounter = tags[ind]['count'] tagIndex = ind return tagIndex def obtainClassifyError(self, tags, index): count_list = list(map(lambda x: x['count'], tags)) total = reduce(lambda a, b: a + b, count_list) return 1 - tags[index]['count'] / total def obtainTotalError(self, tags, index): total = 0 for i in range(len(tags)): if i != index: total += tags[i]['count'] return total def main(self, file, padreArbol): reader = pd.read_excel(file, header=0) columns = reader.columns data_csv = reader._get_values attribute_summarize = [] for column in columns: attribute_summarize.append( util.obtainMetrics(reader[column], column)) if self.shouldStop(attribute_summarize, len(columns)) == True: index = self.obtainTagIndex( attribute_summarize[-1]['disctint_values_name']) clasifyerror_value = self.obtainClassifyError( attribute_summarize[-1]['disctint_values_name'], index) toterror = self.obtainTotalError( attribute_summarize[-1]['disctint_values_name'], index) tag = attribute_summarize[-1]['disctint_values_name'][index][ 'name'] nodo = { 'tag_name': tag, 'classify_error': clasifyerror_value, 'resumen_clases': attribute_summarize[-1]['disctint_values_name'] } if padreArbol == None: self.tree.add(nodo) else: padreArbol.add(nodo) else: attribute_summarize[-1]['entropy'] = util.fatherEntropy( attribute_summarize[-1]['disctint_values_name']) for i in range(len(columns) - 1): util.entropyPerValue(reader[columns[i]], reader[columns[-1]], i, attribute_summarize) for i in range(len(columns) - 1): attribute_summarize[i]['gain_split'] = util.gainSplit( -1, i, attribute_summarize) for i in range(len(columns) - 1): attribute_summarize[i]['split_info'] = util.splitInfo( -1, i, attribute_summarize) for i in range(len(columns) - 1): attribute_summarize[i]['gain_ratio'] = util.gainRatio( i, attribute_summarize) result = util.rootFinder(self.folder, attribute_summarize, data_csv, columns) if padreArbol == None: self.tree.add(result) else: padreArbol.add(result) nodo = self.tree.find(result) for i in range(0, len(result['childs'])): self.main(result['childs'][i]['file'], nodo) # Inicio de metodos auxiliares def getTree(self): i = 0 self.getTreeRecursive(self.result, i) def getTreeRecursive(self, data, ind): if 'name' in data: print(('\t' * ind) + data['name']) if 'label' in data: print(('\t' * (ind + 1)) + data['label']) if 'node' in data: self.getTreeRecursive(data['node'], ind + 1) if 'tag' in data: print(('\t' * (ind + 2)) + 'TAG: ' + str(data['tag']['name'])) if 'childs' in data: for obj in data['childs']: self.getTreeRecursive(obj, ind + 1) def trainingError(self): return self.errorTotal() / self.total_instances def generalizationErrorCalculo(self, error_entrenamiento, cant_hojas): return error_entrenamiento + 1 * (cant_hojas / self.total_instances) def generalizationError(self): return self.generalizationErrorCalculo(self.trainingError(), self.getCantidadHojas()) def getRules(self): algorithm.tree.getRules() def getCantidadHojas(self): return algorithm.tree.cantidadHojas() def errorTotal(self, excepcion=None): if self.tree.root == None: return 0 return self.errorTotalAux(self.tree.root, excepcion) def errorTotalAux(self, nodo, excepcion): if nodo == excepcion: return 0 suma = 0 if nodo.esHoja(): max = float('-inf') for obj in nodo.data['resumen_clases']: if obj['count'] > max: if max != float('-inf'): suma += max max = obj['count'] else: suma += obj['count'] return suma for hijo in nodo.childs: suma += self.errorTotalAux(hijo, excepcion) return suma def postPoda(self): if self.tree.root != None and not self.tree.root.esHoja(): self.postPodaAux(self.tree.root) def postPodaAux(self, nodo): for hijo in nodo.childs: if not hijo.esHoja(): self.postPodaAux(hijo) clases = [] valores = [] for hijo in nodo.childs: if not hijo.esHoja(): return None for tags in hijo.data['resumen_clases']: if not tags['name'] in clases: clases.append(tags['name']) valores.append(tags['count']) else: id = clases.index(tags['name']) valores[id] += tags['count'] suma = 0 max = float('-inf') union = [] idTag = -1 for i in range(len(valores)): if valores[i] > max: if max != float('-inf'): suma += max max = valores[i] idTag = i else: suma += valores[i] union.append({'name': clases[i], 'count': valores[i]}) tag = clases[idTag] error_classificacion = self.obtainClassifyError(union, idTag) error_generalizacion = self.generalizationError() error_withoutme = self.errorTotal(nodo) cant_hijos = nodo.getCantidadHijo() nuevo_error = self.generalizationErrorCalculo( (error_withoutme + suma) / self.total_instances, self.getCantidadHojas() - cant_hijos) if nuevo_error <= error_generalizacion: nodo.childs.clear() nodo.data = { 'tag_name': tag, 'classify_error': error_classificacion, 'resumen_clases': union } def findClass(self, clases_relation, expected_class): index = -1 for i in range(len(clases_relation)): if clases_relation[i]['label'] == expected_class: index = i break return index def validationError(self, file, nodo, clases_relation): reader = pd.read_excel(file, header=0) columns = reader.columns columns_list = columns.tolist() data_csv = reader._get_values total_instances = len(data_csv) total_errors = 0 for i in range(total_instances): obj = data_csv[i] expected_class = int(obj[-1]) if self.findClass(clases_relation, expected_class) == -1: clases_relation.append({ 'label': expected_class, 'relation': [] }) prediced_class = int(self.predictClass(obj, columns_list, nodo)) index = self.findClass(clases_relation, expected_class) if len(clases_relation[index]['relation']) == 0: clases_relation[index]['relation'].append({ 'tag': prediced_class, 'count': 1 }) else: fouded = False for obj2 in clases_relation[index]['relation']: if obj2['tag'] == prediced_class: obj2['count'] += 1 fouded = True # break if fouded == False: clases_relation[index]['relation'].append({ 'tag': prediced_class, 'count': 1 }) if expected_class != prediced_class: total_errors += 1 #print(i+2,"se esperaba",expected_class,'y se recibio', prediced_class) #print('Total de errores de validacion',total_errors,'('+str(total_instances)+')') #print(self.confusion_matrix) return total_errors / total_instances def predictClass(self, obj, columns, nodo): if nodo.esHoja(): return nodo.data['tag_name'] name = nodo.data['name'] indice = columns.index(name) value = obj[indice] for i in range(len(nodo.data['childs'])): label = nodo.data['childs'][i]['label'] if '>' in label and value > float(label[1:]): return self.predictClass(obj, columns, nodo.childs[i]) elif '<' in label and value <= float(label[2:]): return self.predictClass(obj, columns, nodo.childs[i]) def makeConfusionMatrix(self, clases_relation): classes = [] for obj in clases_relation: if obj['label'] not in classes: classes.append(obj['label']) for obj2 in obj['relation']: if obj2['tag'] not in classes: classes.append(obj2['tag']) classes.sort() longitud = len(classes) matriz = np.zeros((longitud, longitud)) for obj in clases_relation: i = classes.index(obj['label']) id2 = self.findClass(clases_relation, obj['label']) for obj2 in clases_relation[id2]['relation']: j = classes.index(obj2['tag']) matriz[i][j] = obj2['count'] return matriz
''' Created on Sep 8, 2011 @author: calvin ''' if __name__ == '__main__': from Tree import Tree tree = Tree(1) tree.add(0, Tree(2)) tree.add(1, Tree(3)) tree.add(2, Tree(4)) child1 = tree.child_at(0) child1.add(0, Tree(5)) print str(tree) print len(tree) tree.remove(1) print str(tree) print len(tree)
class Computer(Player): """ """ def __init__(self, player_name, player_color, depth=3): """ """ Player.__init__(self, player_name, player_color) self.turn = 0 self.depth = depth - 1 self.player_pawn = 1 self.opponent_pawn = 1 self.player_win = 50 self.opponent_win = -50 self.player_locked = 5 self.opponent_locked = 5 self.depth_player = 1 self.depth_opponent = -1 self.tree = Tree() def play(self, grid: Grid): """ """ #print(self.name) empty_square = grid.get_empty_square() max_value = -float('inf') best_move = [] for available_pos_index, available_pos in enumerate(empty_square): #print(possible_grid[possible_result_index]) grid.add_a_pawn(self, available_pos[0], available_pos[1]) value, branch = self.minmax(grid, self.depth, self.adversary) branch.set_pos(available_pos) self.tree.add(branch) if value > max_value: max_value = value best_move = [empty_square[available_pos_index]] elif value == max_value: best_move.append(empty_square[available_pos_index]) grid.cancel_move() self.tree.set_value(max_value) pos = random.choice(best_move) #print(self.color, best_move, len(best_move), len(empty_square)) self.turn += 1 self.tree.write_in_file("./tree/tree " + str(self.name) + str(self.turn) + " turn") self.tree = Tree() return pos def minmax(self, grid: Grid, depth: int, player: Player) -> int: """ """ current_tree = Tree() if grid.is_finished() or depth == 0: #print(grid, "val :", self.eval(grid, depth), "player",player) value = self.eval(grid, depth) current_tree.set_value(value) #grid.cancel_move() return value, current_tree empty_square = grid.get_empty_square() if player.color == self.color: value = [] for available_pos in empty_square: grid.add_a_pawn(self, available_pos[0], available_pos[1]) current_value, branch = self.minmax(grid, depth - 1, player.adversary) branch.set_pos(available_pos) current_tree.add(branch) value.append(current_value) grid.cancel_move() value = max(value) current_tree.set_value(value) return value, current_tree else: value = [] for available_pos in empty_square: grid.add_a_pawn(self.adversary, available_pos[0], available_pos[1]) current_value, branch = self.minmax(grid, depth - 1, player.adversary) branch.set_pos(available_pos) current_tree.add(branch) value.append(current_value) grid.cancel_move() value = min(value) current_tree.set_value(value) return value, current_tree def eval(self, grid: Grid, depth: int) -> int: """ """ #count the pawn owned by every player number_player = 0 number_opponent = 0 for pos_x, line in enumerate(grid.grid): for pos_y, pawn in enumerate(line): if pawn.color is None: continue if pawn.color == self.color: number_player += self.player_pawn else: number_opponent += self.opponent_pawn if grid.is_finished(): continue surround = True for index_x in range(-1, 2): for index_y in range(-1, 2): if not surround: continue other_pos_x = pos_x + index_x other_pos_y = pos_y + index_y if other_pos_x < 0 or other_pos_y < 0: continue if other_pos_x >= grid.grid_length or other_pos_y >= grid.grid_length: continue if grid.grid[other_pos_x][other_pos_y].color is None: surround = False if surround: if grid.grid[pos_x][pos_y].color == self.color: number_player += self.player_locked else: number_opponent += self.opponent_locked #test if the game is finished if grid.is_finished(): if number_player > number_opponent: return self.player_win + depth * self.depth_player + number_player * self.player_locked else: return self.opponent_win + depth * self.depth_opponent + number_opponent * self.player_locked return number_player - number_opponent
class Statement(object): ''' Represents the state of a Bug language statement. ''' def __init__(self): ''' Constructor ''' self._treeRep = Tree(StatementLabel()) def _current(self): ''' Returns the statement label at the root of the statement tree. ''' return self._treeRep.get_root() def add_to_block(self, pos, statement): ''' Adds a statement to the block. ''' self._treeRep.add(pos, statement) def get_from_block(self, pos): ''' Returns the statement at pos from the block. ''' return self._treeRep.child_at(pos) def __len__(self): ''' Returns the length of the block. ''' return self._treeRep.num_children() def kind(self): ''' Returns the statement kind. ''' return self._current().kind def compose_if(self, condition, block): ''' Composes an if statement with condition and block. ''' self._current().kind = Constants._kinds.IF self._current().test = condition self._treeRep.add(0, block) def decompose_if(self): ''' Returns a tuple of the if statement test and block. ''' return (self._current().test, self._treeRep.child_at(0)) def compose_if_else(self, condition, if_block, else_block): ''' Composes an if else statement with condition and true/false blocks. ''' self._current().kind = Constants._kinds.IFELSE self._current().test = condition self._treeRep.add(0, if_block) self._treeRep.add(1, else_block) def decompose_if_else(self): ''' Returns a tuple of the if else statement's test and true/false blocks. ''' return (self._current().test, self._treeRep.child_at(0), self._treeRep.child_at(1)) def compose_while(self, condition, block): ''' Composes a while statement with condition and block. ''' self._current().kind = Constants._kinds.WHILE self._current().test = condition self._treeRep.add(0, block) def decompose_while(self): ''' Returns a tuple of the while statement test and block. ''' return (self._current().test, self._treeRep.child_at(0)) def compose_call(self, instr): ''' Composes a call instruction. ''' self._current().kind = Constants._kinds.CALL self._current().instruction = instr def decompose_call(self): ''' Returns the text of the call. ''' return self._current().instruction def pretty_print(self, indent): ''' Returns a pretty string version of the statement. ''' pretty = "" if self.kind() == Constants._kinds.IF: pretty = " " * indent pretty += "IF " + \ Constants._conditions_text[self._current().test] + \ " THEN\n" + self._treeRep.child_at(0).pretty_print(indent + 5) pretty += " " * indent + "END IF" elif self.kind() == Constants._kinds.IFELSE: pretty = " " * indent pretty += "IF " + \ Constants._conditions_text[self._current().test] + \ " THEN\n" + self._treeRep.child_at(0).pretty_print(indent + 5) pretty += "ELSE\n" + " " * indent + \ self._treeRep.child_at(1).pretty_print(indent + 5) pretty += " " * indent + "END IF" elif self.kind() == Constants._kinds.WHILE: pretty = " " * indent pretty += "WHILE " + \ Constants._conditions_text[self._current().test] + \ " DO\n" + self._treeRep.child_at(0).pretty_print(indent + 5) pretty += " " * indent + "END WHILE" elif self.kind() == Constants._kinds.BLOCK: for i in range(0, self._treeRep.num_children()): pretty += self._treeRep.child_at(i).pretty_print(indent) + "\n" else: # IDENTIFIER pretty = " " * indent pretty += self._current().instruction return pretty def __str__(self): ''' Calls the pretty_print method of the statement. ''' return self.pretty_print(0)
return False if p.val == q.val: return self.isSameTree(p.left, q.left) and self.isSameTree( p.right, q.right) else: return False t1 = Tree() t2 = Tree() ''' for i in range(10): t1.add(i) t2.add(i) ''' t1.add(0) t2.add(1) sol = Solution() r = sol.isSameTree(t1.root, t2.root) print(r) # improvement class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p is None or q is None:
def main(): tree = Tree() for i in range(11): tree.add(i) print(tree_depth(tree.root)) print(is_balanced_tree(tree.root))
def main(): tree = Tree() for i in [10, 5, 10, 4, 7, 0, 1, 0, 0, 1, 0, 2, 3, 3, 1]: tree.add(i) # tree.breath_travel() search_path(tree.root, 22)
def main(): tree = Tree() for i in range(1, 16): tree.add(i) # tree.breath_travel() z_print_tree(tree)
grade(points["tr_create_tree"]) comment("OK -> " + test_name) else: comment("FAIL -> " + test_name) grade(0) except: e = sys.exc_info()[1] comment("FAIL -> " + test_name + "\n" + str(e)) grade(0) # Check Tree.add() test_name = "Tree : add" try: tree = Tree() tree.add(["layer1", "layer2", "layer3"]) tst1 = serialiseTreeNode(tree.root) == "[None,['layer1',['layer2',['layer3']]]]" tree.add(["layer1", "layer2", "layer4"]) tst2 = serialiseTreeNode(tree.root) == "[None,['layer1',['layer2',['layer3'],['layer4']]]]" if tst1 and tst2: grade(points["tr_tree_add"]) comment("OK -> " + test_name) else: comment("FAIL -> " + test_name) grade(0) except: e = sys.exc_info()[1] comment("FAIL -> " + test_name + "\n" + str(e)) grade(0)
from Tree import Tree tree = Tree() print(tree.getRoot().getData()) tree.add(4) print(tree.getRoot().getData()) tree.add(8) tree.add(3) tree.add(2) tree.add(1) tree.add(0) tree.add(6) tree.add(7) tree.add(10) tree.add(6.5) tree.add(9) print(tree.getRoot().getRight().getData()) tree.search(4) tree.search(5) tree.search(6) print(tree.findMaxNum()) print(tree.findMinNum())
class TreeTest(unittest.TestCase): #===============Initial========================== def setUp(self): self.t = Tree(Node("root")) self.t.add(Node("A")) self.t.add(Node("B")) self.t.add(Node("Aa"), self.t.root.children[0]) self.t.add(Node("Ab"), self.t.root.children[0]) self.t.add(Node("Ba"), self.t.root.children[1]) def tearDown(self): del self.t #==============Testing=================== def test_add_to_root(self): before = len(self.t.root.children) self.t.add(Node("value")) after = len(self.t.root.children) self.assertTrue(before + 1 == after) def test_add_to_node(self): node = self.t.root.children[0] before = len(node.children) self.t.add(Node("subvalue"), node) after = len(node.children) self.assertTrue(before + 1 == after) def test_del_from_node(self): before = len(self.t.root.children) self.t.del_node(self.t.root.children[0]) after = len(self.t.root.children) self.assertTrue(before == after + 1) def test_get_nodes(self): self.assertEqual(len(self.t.get_node_list()), 6) def test_find(self): self.assertEqual(self.t.find("Ab").value, "Ab") def test_find_by_value(self): self.assertEqual(len(self.t.find_nodes("A")), 1) self.t.add(Node("A")) self.assertEqual(len(self.t.find_nodes("A")), 2) def test_move(self): b = len(self.t.root.children[1].children) a = len(self.t.root.children[0].children) node_to_move = self.t.root.children[0].children[0] new_parent = self.t.root.children[1] self.t.move_to(node_to_move, new_parent) self.assertEqual(b + 1, len(self.t.root.children[1].children)) self.assertEqual(a - 1, len(self.t.root.children[0].children)) def test_nodes_and_leafs(self): d = self.t.get_nodes_and_leafs() self.assertEqual(len(d["nodes"]), 3) self.assertEqual(len(d["leafs"]), 3) def test_marks(self): self.assertEqual(self.t.find("A").level, None) self.assertEqual(self.t.find("Ab").level, None) self.t.mark_nodes() self.assertEqual(self.t.find("A").level, 1) self.assertEqual(self.t.find("Ab").level, 2)
from Tree import Tree tree = Tree() tree.add(5) tree.add(7) tree.add(4) tree.add(3) tree.add(2) tree.add(5) tree.print()
while len(stack) != 0: left, right = stack.pop() if left is None and right is None: continue elif left is None or right is None: return False elif left.val == right.val: stack.append((left.left, right.right)) stack.append((left.right, right.left)) else: return False return True from Tree import Tree alist = [1,2,2,3,4,4,3] # alist = [1,2,2,None,3,None,3] tree = Tree() for x in alist: tree.add(x) print(tree) sol = Solution() r = sol.isSymmetric(tree.root) print(r)
return -1 right_height = dfs_height(node.right) if right_height == -1: return -1 if abs(left_height - right_height) > 1: return -1 return max(left_height, right_height) + 1 # ----------------------------------------- return dfs_height(root) != -1 from Tree import Tree alist = [1,2,3,3,5,2,2] tree1 = Tree() for x in alist: tree1.add_sorted(x) # unblanced print(tree1) tree2 = Tree() for x in alist: tree2.add(x) # balanced print(tree2) sol = Solution() r1 = sol.isBalanced(tree1.root) r2 = sol.isBalanced(tree2.root) print(r1, r2)
class Statement(object): ''' Represents the state of a Bug language statement. ''' def __init__(self): ''' Constructor ''' self._treeRep = Tree(StatementLabel()) def _current(self): ''' Returns the statement label at the root of the statement tree. ''' return self._treeRep.get_root() def add_to_block(self, pos, statement): ''' Adds a statement to the block. ''' self._treeRep.add(pos, statement) def get_from_block(self, pos): ''' Returns the statement at pos from the block. ''' return self._treeRep.child_at(pos) def __len__(self): ''' Returns the length of the block. ''' return self._treeRep.num_children() def kind(self): ''' Returns the statement kind. ''' return self._current().kind def compose_if(self, condition, block): ''' Composes an if statement with condition and block. ''' self._current().kind = Constants._kinds.IF self._current().test = condition self._treeRep.add(0, block) def decompose_if(self): ''' Returns a tuple of the if statement test and block. ''' return (self._current().test, self._treeRep.child_at(0)) def compose_if_else(self, condition, if_block, else_block): ''' Composes an if else statement with condition and true/false blocks. ''' self._current().kind = Constants._kinds.IFELSE self._current().test = condition self._treeRep.add(0, if_block) self._treeRep.add(1, else_block) def decompose_if_else(self): ''' Returns a tuple of the if else statement's test and true/false blocks. ''' return (self._current().test, self._treeRep.child_at(0), self._treeRep.child_at(1)) def compose_while(self, condition, block): ''' Composes a while statement with condition and block. ''' self._current().kind = Constants._kinds.WHILE self._current().test = condition self._treeRep.add(0, block) def decompose_while(self): ''' Returns a tuple of the while statement test and block. ''' return (self._current().test, self._treeRep.child_at(0)) def compose_call(self, instr): ''' Composes a call instruction. ''' self._current().kind = Constants._kinds.CALL self._current().instruction = instr def decompose_call(self): ''' Returns the text of the call. ''' return self._current().instruction def pretty_print(self, indent): ''' Returns a pretty string version of the statement. ''' pretty = "" if self.kind() == Constants._kinds.IF: pretty = " " * indent pretty += "IF " + \ Constants._conditions_text[self._current().test] + \ " THEN\n" + self._treeRep.child_at(0).pretty_print(indent + 5) pretty += " " * indent + "END IF" elif self.kind() == Constants._kinds.IFELSE: pretty = " " * indent pretty += "IF " + \ Constants._conditions_text[self._current().test] + \ " THEN\n" + self._treeRep.child_at(0).pretty_print(indent + 5) pretty += "ELSE\n" + " " * indent + \ self._treeRep.child_at(1).pretty_print(indent + 5) pretty += " " * indent + "END IF" elif self.kind() == Constants._kinds.WHILE: pretty = " " * indent pretty += "WHILE " + \ Constants._conditions_text[self._current().test] + \ " DO\n" + self._treeRep.child_at(0).pretty_print(indent + 5) pretty += " " * indent + "END WHILE" elif self.kind() == Constants._kinds.BLOCK: for i in range(0, self._treeRep.num_children()): pretty += self._treeRep.child_at(i).pretty_print(indent) + "\n" else: # IDENTIFIER pretty = " " * indent pretty += self._current().instruction return pretty def __str__(self): ''' Calls the pretty_print method of the statement. ''' return self.pretty_print(0)
def test_compare_trees(self): tree1 = Tree() tree2 = Tree() assert tree1.compare_tree(tree2) is True tree1.add(3) assert tree1.compare_tree(tree2) is False tree1.add(4) tree1.add(0) tree1.add(8) tree1.add(2) tree2.add(3) tree2.add(4) tree2.add(0) tree2.add(8) tree2.add(2) assert tree1.compare_tree(tree2) is True tree2.add(10) assert tree1.compare_tree(tree2) is False tree1.add(10) assert tree1.compare_tree(tree2) is True tree1.add(-1) assert tree1.compare_tree(tree2) is False tree2.add(-1) assert tree1.compare_tree(tree2) is True tree1.add(-5) tree2.add(-3) assert tree1.compare_tree(tree2) is False tree2.add(-5) tree1.add(-3) tree1.print_tree()