python - 在python中递归地向字符串添加行

标签 python string recursion

我想添加命令以将图形绘制到字符串。因此,我写了一个递归函数。

def draw(root,string):
    string += 'Commands to draw the root'
    if root.left != None:
        string += 'Commands to draw a left child'
        draw(root.left,string)

    if root.right != None:...#same as for the left child

我很困惑。如果我使用这样的函数,我的字符串不会改变:

>>>a = ''
>>>draw(root,a)
>>>print(a)
>>>a
''

我尝试添加一个“返回字符串”,但在这种情况下,我的函数在完成绘制根、其左子节点和右子节点后停止。

举个例子:

  • 根= 3
  • root.left = 2
  • root.right = 5
  • 2.左=1

    a='' 画(3,a) 一个

预期输出:

'绘制 3 的命令,绘制 2 的命令,绘制 5 的命令,绘制 1 的命令'

最佳答案

您的string arg是函数的局部变量,因此您对其进行的任何重新分配都是函数的局部变量,除非您返回它。 Python 字符串是不可变的,因此您实际上无法修改传入的字符串,您所能做的就是重新分配给它,这会创建一个新的本地字符串对象。

因此,不要将字符串作为参数传递,而是从递归调用中返回它。

我认为这段代码可以满足您的要求。我创建了一个非常简单的 Node 类来测试它。

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def draw(node, depth=0):
    tab = 4 * ' ' * depth
    depth += 1
    string = tab + 'Commands to draw node. ' + node.data +'\n'
    if node.left is not None:
        string += tab + 'Commands to draw a left child.\n'
        string += draw(node.left, depth)
    if node.right is not None:
        string += tab + 'Commands to draw a right child.\n'
        string += draw(node.right, depth)
    return string

tree = Node('A')
tree.left = Node('B')
tree.right = Node('C')
tree.left.left = Node('D')
tree.left.right = Node('E')

s = draw(tree)
print(s)

输出

Commands to draw node. A
Commands to draw a left child.
    Commands to draw node. B
    Commands to draw a left child.
        Commands to draw node. D
    Commands to draw a right child.
        Commands to draw node. E
Commands to draw a right child.
    Commands to draw node. C

关于python - 在python中递归地向字符串添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44334732/

相关文章:

c - while(true) 之前的 printf 消失

python - Python递归函数返回结果消失

用于洗钱检测的 Javascript 递归

java - 递归归并排序仅对数组的一半进行排序

python - 如何使用 python subprocess 命令在不同目录中运行 shell 命令?

java - 在 N 中找到第一个非零数!在 java

python - SQLite的Python身份验证问题

c++ - 如何在 C++ 中获得 std::u8string 的正确长度?

python - 从电子邮件中的标题添加

python - 如何通过python打开一个文件