How do you print tree structure in python?

Why don't you store it as a treelib object and print it out similar to how we print the CHAID tree out here with more relevant node descriptions related to your use case?

([], {0: 809, 1: 500}, (sex, p=1.47145310169e-81, chi=365.886947811, groups=[['female'], ['male']])) ├── (['female'], {0: 127, 1: 339}, (embarked, p=9.17624191599e-07, chi=24.0936494474, groups=[['C', '<missing>'], ['Q', 'S']])) │ ├── (['C', '<missing>'], {0: 11, 1: 104}, <Invalid Chaid Split>) │ └── (['Q', 'S'], {0: 116, 1: 235}, <Invalid Chaid Split>) └── (['male'], {0: 682, 1: 161}, (embarked, p=5.017855245e-05, chi=16.4413525404, groups=[['C'], ['Q', 'S']])) ├── (['C'], {0: 109, 1: 48}, <Invalid Chaid Split>) └── (['Q', 'S'], {0: 573, 1: 113}, <Invalid Chaid Split>)

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

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

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 3

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 4

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 5

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 6

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

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 8

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 9

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 10

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 11

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 12

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 13

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 14

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 15

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 16

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 17

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 18

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 19

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 20

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 21

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 22

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 23

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 24

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 25

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 26

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 27

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 28

def print_tree(self, root): """ Print out a tree in newick format. :param root: The root node of the tree :type root: Node :return: :rtype: """ def process_child(node): toreturn = '' if node.left or node.right: toreturn = '(' if node.left and node.right: toreturn += process_child(node.left) + "," + process_child(node.right) elif node.left: toreturn += process_child(node.left) elif node.right: toreturn += process_child(node.right) if node.left and node.right and node.name: # the root node?? toreturn += ',' elif node.left or node.right: toreturn += ")" if node.name: toreturn += node.name toreturn += ":{}".format(node.distance) return toreturn print(process_child(root) + ");")

Example 29

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 30

def print_tree(branch, level=0): """ Debug routine to print the resulting tree """ if branch["name"]: print " " * level + branch["name"] if branch["children"]: for leaf in branch["children"]: print_tree(leaf, level + 1)

Example 31

def print_tree(tree, indent=0): if tree == [] or node_value(tree) == None: return print('\t'*indent + str(node_value(tree))) print_tree(left_child(tree), indent+1) print_tree(right_child(tree), indent+1)

Example 32

def print_tree_horizontally(current_node, balanced_branches, name_getter, indent='', last='updown'): up, down = balanced_branches(current_node) """ Printing of "up" branch. """ for child in up: next_last = 'up' if up.index(child) == 0 else '' next_indent = '{0}{1}{2}'.format(indent, ' ' if 'up' in last else '│', ' ' * len(name_getter(current_node))) print_tree_horizontally(child, balanced_branches, name_getter, next_indent, next_last) """ Printing of current node. """ if last == 'up': start_shape = '┌' elif last == 'down': start_shape = '└' elif last == 'updown': start_shape = ' ' else: start_shape = '├' if up: end_shape = '┤' elif down: end_shape = '┐' else: end_shape = '' print('{0}{1}{2}{3}'.format(indent, start_shape, name_getter(current_node), end_shape)) """ Printing of "down" branch. """ for child in down: next_last = 'down' if down.index(child) is len(down) - 1 else '' next_indent = '{0}{1}{2}'.format(indent, ' ' if 'down' in last else '│', ' ' * len(name_getter(current_node))) print_tree_horizontally(child, balanced_branches, name_getter, next_indent, next_last)

Example 33

def print_syntax_tree(self, ast): """ Print the syntax tree Arguments : ast : The syntax tree to print """ ast.show(key=lambda a: "")

Example 34

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 35

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 36

def print_tree(self, node, style=anytree.ContRoundStyle()): '''print the tree similar to unix tool "tree"''' rend = anytree.RenderTree(node, childiter=self._sort_tree) for pre, fill, node in rend: self._print_node(node, pre=pre, withdepth=True)

Example 37

def printClsTree(self, root, ident): if root.isInterface: print '*', " " * ident, root.Name for sub in root.SubinterfaceList: self.printClsTree(sub, ident + 4) else: print ' ', " " * ident, root.Name for sub in root.SubclassList: self.printClsTree(sub, ident + 4)

Example 38

def print_tree(part, func=str): """Pretty print a Mime tree For debugging emails func should be a callable that accepts a PartList object as its only argument and returns a string """ indent = "\t" * part.get_level() print("{}{}".format(indent, func(part))) for child in part.get_children(): print_tree(child, func)

Example 39

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

Example 40

def print_tree(self): print(str(self)) if type(self.left) is Node: self.left.print_tree() if type(self.right) is Node: self.right.print_tree()

Example 41

def printTree(self, tree, color): for node in tree.keys(): print(node.id, node.startIdx, node.depth, color[node]) for edge in tree[node].values(): if edge.endNode == None: e = None else: e = edge.endNode.id print(edge.startIdx, edge.endIdx, edge.startNode.id, e, color[edge.endNode], edge.str()) print('')

Example 42

def printTreeDocs(rootTopic=None, topicMgr=None, **kwargs): """Print out the topic tree to a file (or file-like object like a StringIO), starting at rootTopic. If root topic should be root of whole tree, get it from pub.getDefaultTopicTreeRoot(). The treeVisitor is an instance of pub.TopicTreeTraverser. Printing the tree docs would normally involve this:: from pubsub import pub from pubsub.utils.topictreeprinter import TopicTreePrinter traverser = pub.TopicTreeTraverser( TopicTreePrinter(**kwargs) ) traverser.traverse( pub.getDefaultTopicTreeRoot() ) With printTreeDocs, it looks like this:: from pubsub import pub from pubsub.utils import printTreeDocs printTreeDocs() The kwargs are the same as for TopicTreePrinter constructor: extra(None), width(70), indentStep(4), bulletTopic, bulletTopicItem, bulletTopicArg, fileObj(stdout). If fileObj not given, stdout is used.""" if rootTopic is None: if topicMgr is None: from .. import pub topicMgr = pub.getDefaultTopicMgr() rootTopic = topicMgr.getRootAllTopics() printer = TopicTreePrinter(**kwargs) traverser = TopicTreeTraverser(printer) traverser.traverse(rootTopic)

Example 43

def print_json_tree(df, indent=' '): """Prints tree structure of given dict for test/debug purposes""" for key in df.keys(): print(indent+str(key)) if isinstance(df[key], dict): print_json_tree(df[key], indent + ' ')

Example 44

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.node,tuple): return max(rwidth,2 + lwidth + len(str(tree.node)), 2 + lwidth + len(tree[0])) (res,op) = tree.node # Pad to the left with spaces, followed by a sequence of '-' # and the derivation rule. print lwidth*' ' + (rwidth-lwidth)*'-' + str(op) # Print the resulting category on a new line. respadlen = (rwidth - lwidth - len(str(res)))/2 + lwidth print respadlen*' ' + str(res) return rwidth ### Demonstration code # Construct the lexicon

Example 45

def print_tree(root): if root is not None: print(root.val) print_tree(root.left) print_tree(root.right)

Example 46

def print_tree(self): for k in range(1, self.tree_level+1): for j in range(2**(k-1)-1, 2**k-1): print(self.tree[j], end=' ') print()

Example 47

def print_tree(tree): if tree is None: return if(tree.left_child is not None): print_node(tree.left_child) if(tree.right_child is not None): print_node(tree.right_child) print_tree(tree.left_child) print_tree(tree.right_child) return

Example 48

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 49

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 50

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 51

def printTree(self, root): if root is None: return # print(root.data) self.printTree(root.left) self.printTree(root.right)

Example 52

def print_dependency_tree(tree, root, *, indent=0, ctx=None): """ >>> tree = {"a": {"b", "c"}, >>> "b": {"d"}, >>> "c": {"b", "d"}} >>> print_dependency_tree(tree, "a") a ├─b │ └─d └─c ├─b │ └─d └─d """ depth, branches, seen = ctx or (0, [], set()) if depth == 0: print(" "*indent + root) if root not in tree: return branches += [None] seen |= {root} children = set(tree[root]) - seen more = len(children) for child in sorted(children): more -= 1 branches[depth] = ("├" if more else "└") + "─" if child in seen: continue print(" "*indent + "".join(branches) + child) if child in tree: branches[depth] = ("│" if more else " ") + " " ctx = depth + 1, branches.copy(), seen.copy() print_dependency_tree(tree, child, indent=indent, ctx=ctx)

Example 53

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 54

def print_tree(node, depth=0): if isinstance(node, dict): print('%s[X%d < %.2f]' % ((depth*' ', (node['attribute']+1), node['value']))) print_tree(node['left'], depth+1) print_tree(node['right'], depth+1) else: print('%s[%s]' % ((depth*' ', node))) #Function to get prediction from input tree

Example 55

def print_tree(self, node, c=""): c += "\t" print(c + node.get_attribute_name() + " " + str(node.CLASSES_DISTRIBUTIONS)) for branch, child in node.BRANCHES.items(): print(c + ">" + branch + "<") if child.get_attribute_name() is not None: self.print_tree(child, c) else: print(c + str(child.PARENT.get_class()))

Example 56

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 57

def print_tree(task, indent='', last=True, clip_params=False): ''' Return a string representation of the tasks, their statuses/parameters in a dependency tree format ''' # dont 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 = (bcolors.OKGREEN + 'COMPLETE' if is_task_complete else bcolors.OKBLUE + 'PENDING') + bcolors.ENDC name = task.__class__.__name__ params = task.to_str_params(only_significant=True) if len(params)>1 and clip_params: params = next(iter(params.items()), None) # keep only one param params = str(dict([params]))+'[more]' result = '\n' + indent if(last): result += '└─--' indent += ' ' else: result += '|--' indent += '| ' result += '[{0}-{1} ({2})]'.format(name, params, is_complete) children = flatten(task.requires()) for index, child in enumerate(children): result += print_tree(child, indent, (index+1) == len(children), clip_params) return result

Example 58

def printTree(tree): if tree != None: printTree(tree.getLeftChild()) print(tree.getnodeDataValue()) printTree(tree.getRightChild())

Example 59

def print_tree(self, level=None): """Print values for whole tree or at specified level.""" levels = range(self.tree_levels) if level is None else [level] for k in levels: for j in range(2 ** k - 1, 2 ** (k + 1) - 1): print(self.tree[j], end=' ') print() # Helpers.

Example 60

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)

Is there a tree structure in Python?

What is a Tree Data Structure in Python? A Tree is a Data structure in which data items are connected using references in a hierarchical manner. Each Tree consists of a root node from which we can access each element of the tree.

How do you create a tree list in Python?

Given a list of lists, write a Python program to convert the given list of lists into a tree-like dictionary..
Examples:.
Method #1 : Naive Method. This is a Naive approach in which we use two for loops to traverse the list of lists. ... .
Method #2 : Using reduce().

How do you print a binary tree?

You start traversing from the root, then go to the left node, then you again go to the left node until you reach a leaf node. At that point in time, you print the value of the node or mark it as visited and move to the right subtree. Continue the same algorithm until all nodes of the binary tree are visited.

How do you make a binary tree in Python?

The binary search tree is a special type of tree data structure whose inorder gives a sorted list of nodes or vertices. In Python, we can directly create a BST object using binarytree module. bst() generates a random binary search tree and return its root node.

Chủ đề