Python print tree
60 Python code examples are found related to "
print tree".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: binary_search_tree.py From toys with GNU General Public License v2.0 | 11 votes |
def print_tree(root): """未完成!打印出每个节点的value和左右子节点的value,为了下一步打印出树结构做准备 """ quene = [] quene.append(root) while len(quene) != 0 : node = quene[0] if node.left == None: ll = '-' else: ll = node.left.value if node.right == None: rr = '-' else: rr = node.right.value print(' {n} \n _|_ \n| |\n{l} {r}\n==========='.format(n = node.value, l = ll, r = rr)) quene.pop(0) if node.left != None: quene.append(node.left) if node.right != None: quene.append(node.right) print('\n')
Example 2
Source File: tree.py From pyh3 with MIT License | 6 votes |
def print_tree(self): """ Print the tree sorted by depth to log, including the following parameters. The tree is traversed in a breath-first-search. """ current_generation = deque([self.root.node_id]) next_generation = True while next_generation: next_generation = deque() while current_generation: node_id = current_generation.popleft() logging.info( "{0}, parent: {1}, depth: {2}, #children: {3}, size: {4}, radius: {5}, area: {6}" .format(node_id, self.nodes[node_id].parent, self.nodes[node_id].depth, len(self.nodes[node_id].children), self.nodes[node_id].tree_size, self.nodes[node_id].radius, self.nodes[node_id].area)) for child in self.nodes[node_id].children: next_generation.append(child.node_id) current_generation = next_generation
Example 3
Source File: models.py From conllu with MIT License | 6 votes |
def print_tree(self, depth=0, indent=4, exclude_fields=DEFAULT_EXCLUDE_FIELDS): if not self.token: raise ParseException("Can't print, token is None.") if "deprel" not in self.token or "id" not in self.token: raise ParseException("Can't print, token is missing either the id or deprel fields.") relevant_data = self.token.copy() for key in exclude_fields: if key in relevant_data: del relevant_data[key] node_repr = ' '.join([ '{key}:{value}'.format(key=key, value=value) for key, value in relevant_data.items() ]) print(' ' * indent * depth + '(deprel:{deprel}) {node_repr} [{idx}]'.format( deprel=self.token['deprel'], node_repr=node_repr, idx=self.token['id'], )) for child in self.children: child.print_tree(depth=depth + 1, indent=indent, exclude_fields=exclude_fields)
Example 4
Source File: guided_tree.py From fairtest with Apache License 2.0 | 6 votes |
def print_tree(tree, outfile, encoders): """ Print a tree to a file Parameters ---------- tree : the tree structure outfile : the output file encoders : the encoders used to encode categorical features """ import pydot dot_data = StringIO() export_graphviz(tree, encoders, filename=dot_data) graph = pydot.graph_from_dot_data(dot_data.getvalue()) graph.write_pdf(outfile)
Example 5
Source File: dominators.py From equip with Apache License 2.0 | 6 votes |
def print_tree(self, post_dom=False): g_nodes = {} doms = self._doms if not post_dom else self._pdoms g = DiGraph() for node in doms: if node not in g_nodes: cur_node = g.make_add_node(data=node) g_nodes[node] = cur_node cur_node = g_nodes[node] parent = doms.get(node, None) if parent is not None and parent != node: if parent not in g_nodes: parent_node = g.make_add_node(data=parent) g_nodes[parent] = parent_node parent_node = g_nodes[parent] g.make_add_edge(parent_node, cur_node) logger.debug("%sDOM-tree :=\n%s", 'POST-' if post_dom else '', g.to_dot())
Example 6
Source File: preorder_iterative.py From youtube_tutorials with GNU General Public License v3.0 | 6 votes |
def print_tree(self, traversal_type): if traversal_type == "preorder": return self.preorder_print(tree.root, "") elif traversal_type == "inorder": return self.inorder_print(tree.root, "") elif traversal_type == "postorder": return self.postorder_print(tree.root, "") elif traversal_type == "levelorder": return self.levelorder_print(tree.root) elif traversal_type == "reverse_levelorder": return self.reverse_levelorder_print(tree.root) elif traversal_type == "preorder_iterative": return self.preorder_iterative_print(tree.root) else: print("Traversal type " + str(traversal_type) + " is not supported.") return False
Example 7
Source File: nlp_sentence.py From practicalDataAnalysisCookbook with GNU General Public License v2.0 | 6 votes |
def print_tree(tree, filename): ''' A method to save the parsed NLTK tree to a PS file ''' # create the canvas canvasFrame = nltk.draw.util.CanvasFrame() # create tree widget widget = nltk.draw.TreeWidget(canvasFrame.canvas(), tree) # add the widget to canvas canvasFrame.add_widget(widget, 10, 10) # save the file canvasFrame.print_to_file(filename) # release the object canvasFrame.destroy() # two sentences from the article
Example 8
Source File: clidbman.py From gprime with GNU General Public License v2.0 | 6 votes |
def print_family_tree_summaries(self, database_names=None): """ Prints a detailed list of the known family trees. """ print(_('Gramps Family Trees:')) for item in self.current_names: (name, dirpath, path_name, last, tval, enable, stock_id, backend_type, version) = item if (database_names is None or any([(re.match("^" + dbname + "$", name) or dbname == name) for dbname in database_names])): summary = self.get_dbdir_summary(dirpath, name) print(_("Family Tree \"%s\":") % summary[_("Family Tree")]) for item in sorted(summary): if item != "Family Tree": # translators: needed for French, ignore otherwise print(_(" %(item)s: %(summary)s") % { 'item' : item, 'summary' : summary[item]})
Example 9
Source File: cyk_parser.py From CYK-Parser with MIT License | 6 votes |
def print_tree(self, output=True): """ Print the parse tree starting with the start symbol. Alternatively it returns the string representation of the tree(s) instead of printing it. """ start_symbol = self.grammar[0][0] final_nodes = [n for n in self.parse_table[-1][0] if n.symbol == start_symbol] if final_nodes: if output: print("The given sentence is contained in the language produced by the given grammar!") print("\nPossible parse(s):") trees = [generate_tree(node) for node in final_nodes] if output: for tree in trees: print(tree) else: return trees else: print("The given sentence is not contained in the language produced by the given grammar!")
Example 10
Source File: curationsortingextractor.py From spiketoolkit with MIT License | 6 votes |
def print_curation_tree(self, unit_id): '''This function prints the current curation tree for the unit_id (roots are current unit ids). Parameters ---------- unit_id: in The unit id whose curation history will be printed. ''' root_ids = [] for i in range(len(self._roots)): root_id = self._roots[i].unit_id root_ids.append(root_id) if unit_id in root_ids: root_index = root_ids.index(unit_id) print(self._roots[root_index]) else: raise ValueError("invalid unit id")
Example 11
Source File: tree.py From labs with MIT License | 6 votes |
def print_tree(dirpath, indentation): """ Parcurge directorul ce se gaseste la path-ul dirpath si afiseaza numele tuturor instantelor din el. Toate directoarele ce se gasesc in directorul curent, sunt parcurse recursiv. Note: Fisierele sunt precedate de [F], Directoarele sunt precedate de [D], si intrarile necunoscute sunt precedate de [U]. """ new_indentation = indentation + INDENTATION_DIM for filename in os.listdir(dirpath): filepath = os.path.join(dirpath, filename) if os.path.isfile(filepath): print new_indentation + '[F] ' + filename elif os.path.isdir(filepath): print new_indentation + '[D] ' + filename print_tree(filepath, new_indentation) else: print new_indentation + '[U] ' + filename
Example 12
Source File: refbrowser.py From pyFileFixity with MIT License | 6 votes |
def print_tree(self, filename, tree=None): """ Print referrers tree to file (in text format). keyword arguments tree -- if not None, the passed tree will be printed. """ old_stream = self.stream self.stream = open(filename, 'w') try: super(FileBrowser, self).print_tree(tree=tree) finally: self.stream.close() self.stream = old_stream # Code for interactive browser (GUI) # ================================== # The interactive browser requires Tkinter which is not always available. To # avoid an import error when loading the module, we encapsulate most of the # code in the following try-except-block. The InteractiveBrowser itself # remains outside this block. If you try to instantiate it without having # Tkinter installed, the import error will be raised.
Example 13
Source File: Drain.py From logparser with MIT License | 6 votes |
def printTree(self, node, dep): pStr = '' for i in range(dep): pStr += '\t' if node.depth == 0: pStr += 'Root' elif node.depth == 1: pStr += '<' + str(node.digitOrtoken) + '>' else: pStr += node.digitOrtoken print(pStr) if node.depth == self.depth: return 1 for child in node.childD: self.printTree(node.childD[child], dep+1)
Example 14
Source File: order_statistic_tree.py From algorithm with GNU General Public License v2.0 | 6 votes |
def print_tree(self): """ 打印树的结构 :return: """ queue = Queue(self.__root) next_level = 1 now_node_count = 0 while not queue.empty(): cur_node = queue.exit() print str(cur_node) + "\t", now_node_count += 1 if now_node_count == next_level: print now_node_count = 0 next_level *= 2 if cur_node.left is not None: queue.enter(cur_node.left) if cur_node.right is not None: queue.enter(cur_node.right)
Example 15
Source File: print-binary-tree.py From Just-Code with MIT License | 6 votes |
def printTree(self, root): """ :type root: TreeNode :rtype: List[List[str]] """ def get_height(node): return 0 if not node else 1 + max(get_height(node.left), get_height(node.right)) def update_output(node, row, left, right): if not node: return mid = (left + right) // 2 self.output[row][mid] = str(node.val) update_output(node.left, row + 1 , left, mid - 1) update_output(node.right, row + 1 , mid + 1, right) height = get_height(root) width = 2 ** height - 1 self.output = [[''] * width for i in range(height)] update_output(node=root, row=0, left=0, right=width - 1) return self.output
Example 16
Source File: format_tree.py From 4lang with MIT License | 6 votes |
def print_tree(tree): if tree.height() == 2: print("{}( {})".format(tree.label(), tree[0]), end="") #pos, word; Stanford format else: tree_len = len(tree) if tree.label() == "NP" and tree_len > 1: #NP2, NP3... tree.set_label("NP{}".format(tree_len)) print("{}( ".format(tree.label()), end="") index = 1 for subtree in tree: print_tree(subtree) if tree_len > index: print(", ", end="") index += 1 print(")", end="")
Example 17
Source File: folding.py From Turing with MIT License | 6 votes |
def print_tree(editor, file=sys.stdout, print_blocks=False): """ Prints the editor fold tree to stdout, for debugging purpose. :param editor: CodeEdit instance. :param file: file handle where the tree will be printed. Default is stdout. :param print_blocks: True to print all blocks, False to only print blocks that are fold triggers """ block = editor.document().firstBlock() while block.isValid(): trigger = TextBlockHelper().is_fold_trigger(block) trigger_state = TextBlockHelper().is_collapsed(block) lvl = TextBlockHelper().get_fold_lvl(block) visible = 'V' if block.isVisible() else 'I' if trigger: trigger = '+' if trigger_state else '-' print('l%d:%s%s%s' % (block.blockNumber() + 1, lvl, trigger, visible), file=file) elif print_blocks: print('l%d:%s%s' % (block.blockNumber() + 1, lvl, visible), file=file) block = block.next()
Example 18
Source File: local.py From edx-analytics-pipeline with GNU Affero General Public License v3.0 | 6 votes |
def print_dependency_tree(task, indent='', last=True): """Return a string representation of the tasks, their statuses/parameters in a dependency tree format.""" # Don't bother printing out warnings about tasks with no output. with warnings.catch_warnings(): warnings.filterwarnings(action='ignore', message='Task .* without outputs has no custom complete\(\) method') is_task_complete = task.complete() is_complete = 'COMPLETE' if is_task_complete else 'PENDING' name = task.__class__.__name__ params = task.to_str_params(only_significant=True) result = '\n' + indent if last: result += '└─--' indent += ' ' else: result += '|--' indent += '| ' result += '[{0}-{1} ({2})]'.format(name, params, is_complete) children = task.deps() for index, child in enumerate(children): result += print_dependency_tree(child, indent, (index + 1) == len(children)) return result
Example 19
Source File: decision_tree_regression_traverse_batch.py From daal4py with Apache License 2.0 | 6 votes |
def printTree(nodes, values): def printNodes(node_id, nodes, values, level): node = nodes[node_id] value = values[node_id] if not math.isnan(node["threshold"]): print(" " * level + "Level " + str(level) + ": Feature = " + str(node["feature"]) + ", Threshold = " + str(node["threshold"])) else: print(" " * level + "Level " + str(level) + ", Value = " + str(value).replace(" ", "")) if node["left_child"] != -1: printNodes(node["left_child"], nodes, values, level + 1) if node["right_child"] != -1: printNodes(node["right_child"], nodes, values, level + 1) return printNodes(0, nodes, values, 0) return
Example 20
Source File: ofxpostern.py From ofxpostern with GNU General Public License v3.0 | 6 votes |
def print_tree(tree, lvl=1): ''' Print embedded lists as an indented text tree Recursive to depth 3 tree: list[val, list[]...] ''' indent = 2 bullet = '' if lvl == 1: bullet = '*' elif lvl == 2: bullet = '+' elif lvl == 3: bullet = '-' else: raise ValueError('Unknown lvl: {}'.format(lvl)) for i in tree: if type(i) is list: print_tree(i, lvl+1) else: print('{}{} {}'.format(' '*(indent*(lvl-1)), bullet, i))
Example 21
Source File: cellblender_main.py From cellblender with GNU General Public License v2.0 | 6 votes |
def print_id_property_tree ( self, obj, name, depth ): """ Recursive routine that prints an ID Property Tree """ depth = depth + 1 indent = "".join([ ' ' for x in range(depth) ]) print ( indent + "Depth="+str(depth) ) print ( indent + "print_ID_property_tree() called with \"" + name + "\" of type " + str(type(obj)) ) if "'IDPropertyGroup'" in str(type(obj)): print ( indent + "This is an ID property group: " + name ) for k in obj.keys(): self.print_id_property_tree ( obj[k], k, depth ) elif "'list'" in str(type(obj)): print ( indent + "This is a list: " + name ) i = 0 for k in obj: self.print_id_property_tree ( k, name + '['+str(i)+']', depth ) i += 1 else: print ( indent + "This is NOT an ID property group: " + name + " = " + str(obj) ) depth = depth - 1 return
Example 22
Source File: shallow_parsing.py From text-analytics-with-python with Apache License 2.0 | 6 votes |
def print_sentence_tree(sentence_tree): processed_tree = process_sentence_tree(sentence_tree) processed_tree = [ Tree( item[0], [ Tree(x[1], [x[0]]) for x in item[1] ] ) for item in processed_tree ] tree = Tree('S', processed_tree ) print tree
Example 23
Source File: tree.py From active-learning with Apache License 2.0 | 6 votes |
def print_tree(self, node, max_depth): """Helper function to print out tree for debugging.""" node_list = [node] output = "" level = 0 while level < max_depth and len(node_list): children = set() for n in node_list: node = self.get_node(n) output += ("\t"*level+"node %d: score %.2f, weight %.2f" % (node.name, node.score, node.weight)+"\n") if node.left: children.add(node.left.name) if node.right: children.add(node.right.name) level += 1 node_list = children return print(output)
Example 24
Source File: __init__.py From mathAI with MIT License | 6 votes |
def print_parser_tree(node,latex_str): if isinstance(node,dict) and len(node) and isinstance(node['structure'],list): for child in node['structure']: latex_str = print_parser_tree(child,latex_str) elif isinstance(node,dict) and len(node): print(node['structure'],end='') latex_str = latex_str + str(node['structure']) else: if node == 'div': print('/',end = '') latex_str = latex_str + "\\div" elif node == 'times': print('*',end='') latex_str = latex_str + "\\times" else: print(node,end='') latex_str = latex_str + node return latex_str # 定义从解到输出结果的格式
Example 25
Source File: decision_tree.py From ML-From-Scratch with MIT License | 6 votes |
def print_tree(self, tree=None, indent=" "): """ Recursively print the decision tree """ if not tree: tree = self.root # If we're at leaf => print the label if tree.value is not None: print (tree.value) # Go deeper down the tree else: # Print test print ("%s:%s? " % (tree.feature_i, tree.threshold)) # Print the true scenario print ("%sT->" % (indent), end="") self.print_tree(tree.true_branch, indent + indent) # Print the false scenario print ("%sF->" % (indent), end="") self.print_tree(tree.false_branch, indent + indent)
Example 26
Source File: pptree.py From pptree with MIT License | 6 votes |
def print_tree(current_node, childattr='children', nameattr='name', horizontal=True): if hasattr(current_node, nameattr): name = lambda node: getattr(node, nameattr) else: name = lambda node: str(node) children = lambda node: getattr(node, childattr) nb_children = lambda node: sum(nb_children(child) for child in children(node)) + 1 def balanced_branches(current_node): size_branch = {child: nb_children(child) for child in children(current_node)} """ Creation of balanced lists for "a" branch and "b" branch. """ a = sorted(children(current_node), key=lambda node: nb_children(node)) b = [] while a and sum(size_branch[node] for node in b) < sum(size_branch[node] for node in a): b.append(a.pop()) return a, b if horizontal: print_tree_horizontally(current_node, balanced_branches, name) else: print_tree_vertically(current_node, balanced_branches, name, children)
Example 27
Source File: chart.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def printCCGTree(lwidth,tree): rwidth = lwidth # Is a leaf (word). # Increment the span by the space occupied by the leaf. if not isinstance(tree,Tree): return 2 + lwidth + len(tree) # Find the width of the current derivation step for child in tree: rwidth = max(rwidth, printCCGTree(rwidth,child)) # Is a leaf node. # Don't print anything, but account for the space occupied. if not isinstance(tree.label(), tuple): return max(rwidth,2 + lwidth + len("%s" % tree.label()), 2 + lwidth + len(tree[0])) (res,op) = tree.label() # Pad to the left with spaces, followed by a sequence of '-' # and the derivation rule. print(lwidth*' ' + (rwidth-lwidth)*'-' + "%s" % op) # Print the resulting category on a new line. str_res = "%s" % res respadlen = (rwidth - lwidth - len(str_res)) // 2 + lwidth print(respadlen*' ' + str_res) return rwidth ### Demonstration code # Construct the lexicon
Example 28
Source File: eval_util.py From tsinfer with GNU General Public License v3.0 | 5 votes |
def print_tree_pairs(ts1, ts2, compute_distances=True): """ Prints out the trees at each point in the specified tree sequences, alone with their KC distance. """ weighted_distance = 0 total_mismatch_interval = 0 total_mismatches = 0 for (left, right), tree1, tree2 in tree_pairs(ts1, ts2): print("-" * 20) print("Interval =", left, "--", right) print("Source interval =", tree1.interval) print("Inferred interval =", tree2.interval) if compute_distances: distance = tree1.kc_distance(tree2) weighted_distance += (right - left) * distance trailer = "" if distance != 0: total_mismatch_interval += right - left total_mismatches += 1 trailer = "[MISMATCH over {:.2f}]".format(right - left) print("KC distance =", distance, trailer) print() d1 = tree1.draw(format="unicode").splitlines() d2 = tree2.draw(format="unicode").splitlines() j = 0 while j < (min(len(d1), len(d2))): print(d1[j], " | ", d2[j]) j += 1 while j < len(d1): print(d1[j], " |") j += 1 while j < len(d2): print(" " * len(d1[0]), " | ", d2[j]) j += 1 print() print("Total weighted tree distance = ", weighted_distance) print("Total mismatch interval = ", total_mismatch_interval) print("Total mismatches = ", total_mismatches)
Example 29
Source File: files.py From rekall with GNU General Public License v2.0 | 5 votes |
def print_component_tree(tree, depth=""): """This is used for debugging the component_tree.""" if not tree: return for k, v in tree.items(): print("%s %s:" % (depth, k)) print_component_tree(v, depth + " ")
Example 30
Source File: file_util.py From tools with GNU General Public License v2.0 | 5 votes |
def print_tree(comments,tree,out): if comments: print >> out, u"\n".join(comments) for cols in tree: print >> out, u"\t".join(cols) print >> out
Example 31
Source File: 16_DS_Part_2.py From Python with MIT License | 5 votes |
def printTree(self): print('\n\nPreOrder Traversal (Root, Left, Right)') self.preOrder(self.headNode) print('\n\nInOrder Traversal (Left, Root, Right)') self.inOrder(self.headNode) print('\n\nPostOrder Traversal (Left, Right, Root)') self.postOrder(self.headNode)
Example 32
Source File: CTMagic.py From CapTipper with GNU General Public License v3.0 | 5 votes |
def print_tree(self,Node, index): for nd in Node.children: print "--" * index + nd.byte if (len(nd.children) > 0): self.print_tree(nd, index + 1)
Example 33
Source File: 爬取QQ企业邮箱成员邮箱地址.py From fuzzdb-collect with GNU General Public License v3.0 | 5 votes |
def print_tree(id, department_infos, level, staff_infors, f): prefix = '----' * level text = prefix + department_infos[id]['name'] + prefix print text f.write(text + '\n') for key, value in department_infos.items(): if value['pid'] == id: print_tree(value['id'], department_infos, level+1, staff_infors, f) prefix = ' ' * level for staff in staff_infors: if staff['pid'] == id: text = prefix + staff['name'] + ' ' + staff['alias'] print text f.write(text + '\n')
Example 34
Source File: module_tree.py From msticpy with MIT License | 5 votes |
def print_call_tree(call_graph: nx.Graph, level="top"): """ Print out the call tree. Parameters ---------- call_graph : [type] [description] level : str, optional [description], by default "top" """ for node in call_graph.nodes(): if level == "top": if call_graph.in_degree(node) == 0: print( f"\n{node} [{call_graph.nodes()[node]['start']}", f"- {call_graph.nodes()[node]['end']}]", ) print("-" * len(str(node))) _print_decendents(call_graph, node, indent=0) elif "start" in call_graph.nodes()[node]: print( f"\n{node} [{call_graph.nodes()[node]['start']}-{call_graph.nodes()[node]['end']}]" ) print("-" * len(str(node))) _print_decendents(call_graph, node, indent=0)
Example 35
Source File: behaviortree.py From gaige with MIT License | 5 votes |
def printTree(self): if self.tree is not None: self.tree.printTree() ### Called every tick. Calls tree.execute(), which will return True for successful completion, False for failed execution, or None if execution should continue next tick. If the tree completes execution (i.e., returns True or False), then the tree is reset to begin again in the next tick.
Example 36
Source File: pstree.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def print_tree(parent, tree, indent=''): try: name = psutil.Process(parent).name() except psutil.Error: name = "?" print(parent, name) if parent not in tree: return children = tree[parent][:-1] for child in children: sys.stdout.write(indent + "|- ") print_tree(child, tree, indent + "| ") child = tree[parent][-1] sys.stdout.write(indent + "`_ ") print_tree(child, tree, indent + " ")
Example 37
Source File: utils.py From mne-bids with BSD 3-Clause "New" or "Revised" License | 5 votes |
def print_dir_tree(folder, max_depth=None): """Recursively print dir tree starting from `folder` up to `max_depth`.""" if not op.exists(folder): raise ValueError('Directory does not exist: {}'.format(folder)) msg = '`max_depth` must be a positive integer or None' if not isinstance(max_depth, (int, type(None))): raise ValueError(msg) if max_depth is None: max_depth = float('inf') if max_depth < 0: raise ValueError(msg) # Use max_depth same as the -L param in the unix `tree` command max_depth += 1 # Base length of a tree branch, to normalize each tree's start to 0 baselen = len(folder.split(os.sep)) - 1 # Recursively walk through all directories for root, dirs, files in os.walk(folder): # Check how far we have walked branchlen = len(root.split(os.sep)) - baselen # Only print, if this is up to the depth we asked if branchlen <= max_depth: if branchlen <= 1: print('|{}'.format(op.basename(root) + os.sep)) else: print('|{} {}'.format((branchlen - 1) * '---', op.basename(root) + os.sep)) # Only print files if we are NOT yet up to max_depth or beyond if branchlen < max_depth: for file in files: print('|{} {}'.format(branchlen * '---', file))
Example 38
Source File: ml_decision_tree.py From Grokking-Artificial-Intelligence-Algorithms with GNU Affero General Public License v3.0 | 5 votes |
def print_tree(node, indentation=''): # The examples in the current ExamplesNode if isinstance(node, ExamplesNode): print(indentation + 'Examples', node.examples) return # The question for the current DecisionNode print(indentation + str(node.question.to_string())) # Find the 'True' examples for the current DecisionNode recursively print(indentation + '---> True:') print_tree(node.branch_true, indentation + '\t') # Find the 'False' examples for the current DecisionNode recursively print(indentation + '---> False:') print_tree(node.branch_false, indentation + '\t')
Example 39
Source File: tree.py From Computable with MIT License | 5 votes |
def print_tree(node): """ Prints a tree representation of "node". Examples ======== >>> from sympy.printing import print_tree >>> from sympy.abc import x >>> print_tree(x**2) # doctest: +SKIP Pow: x**2 +-Symbol: x | comparable: False +-Integer: 2 real: True nonzero: True comparable: True commutative: True infinitesimal: False unbounded: False noninteger: False zero: False complex: True bounded: True rational: True integer: True imaginary: False finite: True irrational: False <BLANKLINE> See also: tree() """ print(tree(node))
Example 40
Source File: optimal_binary_search_tree.py From Python with MIT License | 5 votes |
def print_binary_search_tree(root, key, i, j, parent, is_left): """ Recursive function to print a BST from a root table. >>> key = [3, 8, 9, 10, 17, 21] >>> root = [[0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 3], [0, 0, 2, 3, 3, 3], \ [0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 4, 5], [0, 0, 0, 0, 0, 5]] >>> print_binary_search_tree(root, key, 0, 5, -1, False) 8 is the root of the binary search tree. 3 is the left child of key 8. 10 is the right child of key 8. 9 is the left child of key 10. 21 is the right child of key 10. 17 is the left child of key 21. """ if i > j or i < 0 or j > len(root) - 1: return node = root[i][j] if parent == -1: # root does not have a parent print(f"{key[node]} is the root of the binary search tree.") elif is_left: print(f"{key[node]} is the left child of key {parent}.") else: print(f"{key[node]} is the right child of key {parent}.") print_binary_search_tree(root, key, i, node - 1, key[node], True) print_binary_search_tree(root, key, node + 1, j, key[node], False)
Example 41
Source File: P62_BinaryTree.py From Python-Programs with GNU General Public License v3.0 | 5 votes |
def printTree(tree): if tree != None: printTree(tree.getLeftChild()) print(tree.getnodeDataValue()) printTree(tree.getRightChild())
Example 42
Source File: simpletree.py From nzb-subliminal with GNU General Public License v3.0 | 5 votes |
def printTree(self, indent=0): tree = '\n|%s%s' % (' '* indent, unicode(self)) for child in self.childNodes: tree += child.printTree(indent + 2) return tree
Example 43
Source File: _layoutbox.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def print_tree(lb): ''' Print the tree of layoutboxes ''' if lb.parent is None: print('LayoutBox Tree\n') print('==============\n') print_children(lb) print('\n') else: print_tree(lb.parent)
Example 44
Source File: bst.py From challenge-hackerrank30 with The Unlicense | 5 votes |
def printTree(self, root): if root is None: return # print(root.data) self.printTree(root.left) self.printTree(root.right)
Example 45
Source File: GoSyncDriveTree.py From gosync with GNU General Public License v2.0 | 5 votes |
def PrintTree(self, folder_id): pnode = self.FindFolder(folder_id) if not pnode: return children = pnode.GetChildren() for child in children: if child: self.PrintTree(child.GetId()) print("%s" % pnode.GetName()) #DRIVER CODE #tree = GoogleDriveTree() #tree.AddFolder('root', 'aaaa', 'a', None) #tree.AddFolder('aaaa', 'bbbb', 'a/b', None) #tree.AddFolder('aaaa', 'nnnn', 'a/n', None) #tree.AddFolder('aaaa', 'oooo', 'a/o', None) #tree.AddFolder('bbbb', 'cccc', 'a/b/c', None) #tree.AddFolder('bbbb', 'llll', 'a/b/l', None) #tree.AddFolder('bbbb', 'mmmm', 'a/b/m', None) #tree.AddFolder('cccc', 'dddd', 'a/b/c/d', None) #tree.AddFolder('dddd', 'eeee', 'a/b/c/d/e', None) #tree.AddFolder('eeee', 'ffff', 'a/b/c/d/e/f', None) #tree.AddFolder('ffff', 'gggg', 'a/b/c/d/e/f/g', None) #tree.AddFolder('gggg', 'hhhh', 'a/b/c/d/e/f/g/h', None) #tree.AddFolder('hhhh', 'iiii', 'a/b/c/d/e/f/g/h/i', None) #tree.AddFolder('iiii', 'jjjj', 'a/b/c/d/e/f/g/h/i/j', None) #tree.AddFolder('jjjj', 'kkkk', 'a/b/c/d/e/f/g/h/i/j/k', None) # #tree.PrintTree('root') #print("++++++++++++++++++++++++++++") #tree.DeleteFolder('aaaa') #print("----------------------------") #tree.DeleteFolder('aaaa') #print("============================") #tree.PrintTree('root')
Example 46
Source File: Spreadsheet.py From koala with GNU General Public License v3.0 | 5 votes |
def print_value_tree(self,addr,indent): cell = self.cellmap[addr] print("%s %s = %s" % (" "*indent,addr,cell.value)) for c in self.G.predecessors_iter(cell): self.print_value_tree(c.address(), indent+1)
Example 47
Source File: knn.py From Machine_Learning with GNU General Public License v2.0 | 5 votes |
def printTree(self, tree): Q = [tree] while len(Q) != 0: p = Q.pop(0) print str(p.node) if p.left != None: Q.append(p.left) if p.right != None: Q.append(p.right) # ----------------------------------------------------------
Example 48
Source File: snippet.py From Jandroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
def PrintTree(self, indent=0, stream=sys.stdout): stream.write(' ' * indent) if not self.tokens: print >> stream, self.type_name return print >> stream, '%-4s' % self.type_name, repr(self.tokens[0].string) for tok in self.tokens[1:]: stream.write(' ' * indent) print >> stream, ' ' * max(len(self.type_name), 4), repr(tok.string)
Example 49
Source File: output.py From importlab with Apache License 2.0 | 5 votes |
def print_tree(import_graph): def _print_tree(root, indent=0): if root in seen: return seen.add(root) print(format_node(import_graph, root, indent)) for _, v in import_graph.graph.out_edges([root]): _print_tree(v, indent=indent+2) seen = set() for root in nx.topological_sort(import_graph.graph): if not import_graph.graph.in_edges([root]): _print_tree(root)
Example 50
Source File: charcoal.py From Charcoal with MIT License | 5 votes |
def PrintTree(tree, padding="", print=warn): """ PrintTree(tree, padding="") Print tree with the given padding on the left. Trees are of the form [name, children] where children is a list and \ name is not. """ padding = re.sub(r"└$", r" ", re.sub(r"├$", r"│", padding)) new_padding = padding + "├" if len(tree) > 1: for item in tree[1:-1]: if isinstance(item, list): print(new_padding + item[0]) PrintTree(item, new_padding, print) else: if isinstance(item, str): print(new_padding + repr(item)[1:-1]) else: print(new_padding + str(item)) new_padding = padding + "└" item = tree[-1] if isinstance(item, list): print(new_padding + item[0]) PrintTree(item, new_padding, print) else: if isinstance(item, str): print(new_padding + repr(item)[1:-1]) else: print(new_padding + str(item))
Example 51
Source File: statements.py From pyang with ISC License | 5 votes |
def print_tree(stmt, substmts=True, i_children=True, indent=0): istr = " " print("%s%s %s %s %s" % (indent * istr, stmt.keyword, stmt.arg, stmt, stmt.parent)) if substmts and stmt.substmts: print("%s substatements:" % (indent * istr)) for s in stmt.substmts: print_tree(s, substmts, i_children, indent+1) if i_children and hasattr(stmt, 'i_children'): print("%s i_children:" % (indent * istr)) for s in stmt.i_children: print_tree(s, substmts, i_children, indent+1)
Example 52
Source File: qasmparser.py From qiskit-terra with Apache License 2.0 | 5 votes |
def print_tree(self): """Print parsed OPENQASM.""" if self.qasm is not None: self.qasm.to_string(0) else: print("No parsed qasm to print")
Example 53
Source File: plot.py From Xpedite with Apache License 2.0 | 5 votes |
def printTxnPlotTree(txnPlotTree): """Displays a hierarchical view of transaction latency""" import pprint pp = pprint.PrettyPrinter(indent=2) pp.pprint(txnPlotTree)
Example 54
Source File: printo.py From phylowgs with GNU General Public License v3.0 | 5 votes |
def print_best_tree(tssb,fout): nodes = tssb.get_nodes() nnodes = sum( [ 1 for node in nodes if len(node.get_data()) ] ) #fout=open(fout,'w') t = Tree();t.name='0' fout.write('id, \t phi, \t nChildren, \t nGenes, \t genes \n') print_node2(tssb.root,None,t,fout) fout.write('\n\n') fout.write(t.get_ascii(show_internal=True)) fout.write('\n\n') fout.write('Number of non-empty nodes in the tree: ' +repr(nnodes)) fout.write('\n\n\n') #fout.close()
Example 55
Source File: printo.py From phylowgs with GNU General Public License v3.0 | 5 votes |
def print_best_tree_pdf(tssb,fout,score=0): #wts, nodes = tssb.get_mixture() #w = dict([(n[1], n[0]) for n in zip(wts,nodes)]) print_tree_latex(tssb,fout,score) ################ LATEX PRINTING ######################
Example 56
Source File: rdf_triple.py From RDF-Triple-API with MIT License | 5 votes |
def print_tree(self, t, depth=0): try: t.label() except AttributeError: print t # print 'error', t pass else: # Now we know that t.node is defined print '('#, t.label(), t.leaves()[0] for child in t: self.print_tree(child, depth+1) print ') '
Example 57
Source File: Gene.py From rmats2sashimiplot with GNU General Public License v2.0 | 5 votes |
def printTree(tree, depth = 0): if tree == None or not type(tree) == dict: print "\t" * depth, tree else: for key, val in tree.items(): print "\t" * depth, key printTree(val, depth+1)
Example 58
Source File: 3.py From algorithm_course with GNU General Public License v3.0 | 5 votes |
def printTree(root): q, ans = [], [] q.append(root) while q: cur = q.pop(0) if cur: q.append(cur.left) q.append(cur.right) ans.append(cur.val) else: ans.append('#') print(ans)
Example 59
Source File: genetree.py From TALON with MIT License | 5 votes |
def print_tree(self): """ Print a rudimentary visual representation of the GeneTree. """ for chrom in self.chromosomes: print(chrom + ":") for gene_interval in self.chromosomes[chrom]: print("\t" + str(gene_interval)) return