2017-06-02 68 views
1

我想添加命令來繪製圖形到字符串。因此,我寫了一個遞歸函數。在python中遞歸地添加行到字符串

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.left = 1

    a='' draw(3,a) a

預期輸出:

'Commands to draw 3, Commands to draw 2, Commands to draw 5, Commands to draw 1'

+0

我知道這只是一個例子,但是''2.left沒有太大的意義在Python。 –

回答

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 
+0

我忘記了:string + = draw(node.left) 我只是做了:draw(node.left),它應該不會改變一件事情。 –

1

你需要返回它在funtion的局部範圍otherwhise您的修改入住..

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 
    return string 

然後

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

我試過了,最後是根和它的直接子女。子樹不見了。 –