打印带有缩进的树

洛赞斯基

我想打印出一个描述乐队的简单树。我首先创建一个名为“ Band”的节点,然后使它的子级为“ Wind instrument”,而子级又将其子级为“ Saxophone”和“ Trumpet”。然后,我对名为“ Song”的“风乐器”进行兄弟操作,依此类推。该代码非常简单:

class Node:                                     
    value = ""
    down = None
    right = None
def write(p):
    if p==None:
        return
    print(p.value)
    if p.down!=None:        #My idea is that if we go down the tree, we indent first
        print("    ",end="")     
        write(p.down)
    write(p.right)      #If we don't go down, we simply write out the siblings
a=Node()
a.value="Band"
a.down=Node()
a.down.value="Wind instruments"
a.down.down=Node()
a.down.down.value="Saxophone"
a.down.down.right=Node()
a.down.down.right.value="Trumpet"
a.down.right=Node()
a.down.right.value="Song"
a.down.right.right=Node()
a.down.right.right.value="String instruments"
a.down.right.right.down=Node()
a.down.right.right.down.value="Guitar"
a.down.right.right.down.right=Node()
a.down.right.right.down.right.value="Bass"
write(a)

输出为:

Band
    Wind instruments
    Saxophone
Trumpet
Song
String instruments
    Guitar
Bass

但我希望输出为:

Band
    Wind instruments
        Saxophone
        Trumpet
    Song
    String instruments
        Guitar
        Bass

任何人都有一个想法如何实现这一目标?

mo

要根据递归级别进行缩进打印,技巧是使用一个参数来保持递归时的级别:

# default with a level of 0, and an indent of 4 characters
def write(p, depth=0, indent=4):
    if p==None:
        return
    # here we multiply the level by the number of indents
    # and then you multiply that number with a space character
    # which will magically show as that number of spaces.
    print("{}{}".format(" "*(indent*depth), p.value))
    if p.down!=None:
        # then you do not need your print(…, end='') hack
        # simply increase the depth
        write(p.down, depth=depth+1, indent=indent)
    # and for siblings, do not increase the depth
    write(p.right, depth=depth, indent=indent)

我在这里使用的技巧是,默认情况下,级别为0,并且随着深入,您将传递的参数增加1来增加深度。

然后,当您要打印缩进时,您要做的就是将缩进字符串乘以该值(以及缩进大小),这样便可以根据需要打印出缩进:

>>> "A"*42
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'

因此,结果是:

>>> write(a)
Band
    Wind instruments
        Saxophone
        Trumpet
    Song
    String instruments
        Guitar
        Bass

如果想缩小范围,因为有很多递归:

>>> write(a, indent=1)
Band
 Wind instruments
  Saxophone
  Trumpet
 Song
 String instruments
  Guitar
  Bass

作为奖励,我建议您将write()函数用作Node类的一种方法如果您重命名它__str__

class Node:
    value = ""
    down = None
    right = None

    # converts a node into a string
    def as_str(self, depth=0, indent=4):
        # building the current node's line, and add it to a list
        ret = ["{}{}".format(" "*(indent*depth), self.value)]
        if self.down:
            # append down recursion first to the list
            ret.append(self.down.as_str(depth=depth+1, indent=indent))
        if self.right:
            # then append right recursion to the list
            ret.append(self.right.as_str(depth=depth, indent=indent))
        # build the new string, joining each element of the list with a newline
        return "\n".join(ret)

    # a handler for printing the list nicely
    def __str__(self):
        return self.as_str()

    def as_repr(self, depth=0, max_depth=2):
        # building the current node's line, and add it to a list
        ret = ["'{}'".format(self.value)]
        if depth > max_depth:
            ret.append("…")
        else:
            if self.down:
                # append down recursion first to the list
                ret.append(self.down.as_repr(depth=depth+1, max_depth=max_depth))
            if self.right:
                # then append right recursion to the list
                ret.append(self.right.as_repr(depth=depth, max_depth=max_depth))
            # build the new string, joining each element of the list with a newline
        return "Node<{}>".format(",".join(ret))

    # you might want to also make the repr() nicer
    def __repr__(self):
        return self.as_repr()

结果:

>>> a
Node<'Band',Node<'Wind instruments',Node<'Saxophone',…>,Node<'Song',Node<'String instruments',Node<'Guitar',…>>>>>
>>> print(a)
Band
    Wind instruments
        Saxophone
        Trumpet
    Song
    String instruments
        Guitar
        Bass

高温超导

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

无法打印带有缩进的二叉树

来自分类Dev

numpy:打印带有缩进的数组

来自分类Dev

蚂蚁:不要打印带有回声或失败的build.xml缩进

来自分类Dev

仅在树命令中使用空格打印缩进

来自分类Dev

生成带有文本的缩进属性值

来自分类Dev

生成带有适当缩进的XML文件

来自分类Dev

带有缩进的Pyspark textFile json

来自分类Dev

内联描述列表,带有悬挂缩进

来自分类Dev

带有缩进的正确C函数格式

来自分类Dev

在C ++中以指定的缩进级别打印二叉树

来自分类Dev

由于“折叠”功能不足以编写带有缩进的树状漂亮打印机,因此什么是高阶组合器?

来自分类Dev

使用带有 open= 的打印

来自分类Dev

带有热图的圆形树

来自分类Dev

输出带有数组的HTML树

来自分类Dev

带有N个叶子的Java树?

来自分类Dev

带有来宾组件的父子组件树

来自分类Dev

带有javascript的组合框下拉树?

来自分类Dev

带有yasnippet,Emacs的python模式下的错误缩进

来自分类Dev

SASS输出中带有制表符的缩进

来自分类Dev

Sublime Text 3中带有空格缩进的Backspace

来自分类Dev

带有左缩进的MigraDoc表边框问题

来自分类Dev

Inno Setup:保存带有缩进的XML文档

来自分类Dev

C ++中带有顺序括号的Emacs缩进

来自分类Dev

带有左缩进的MigraDoc表边框问题

来自分类Dev

Java缩进打印

来自分类Dev

d3.js如何使所有节点在可折叠缩进树中折叠

来自分类Dev

是否有用于设备树源(.dts,.dtsi)文件的自动缩进工具?

来自分类Dev

二叉树:迭代有序打印

来自分类Dev

打印二叉搜索树的所有叶节点