1
votes

I want to add commands to draw a graph to a string. Therefore, I wrote a recursive function.

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

I'm confused. If I use the function like this, my string doesnt change:

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

I tried to add a "return string", but in that case my function stops after its done with drawing the root, its left and its right child.

As an example:

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

    a='' draw(3,a) a

expected output:

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

2
I know it's just an example, but 2.left doesn't make much sense in Python. - PM 2Ring

2 Answers

1
votes

Your string arg is a local variable of the function, so any reassignments you make to it are local to the function unless you return it. Python strings are immutable so you can't actually modify the string that gets passed in, all you can do is reassign to it, which creates a new local string object.

So rather than passing the string as an arg, return it from the recursive calls.

I think this code does what you want. I've created a very simple Node class to test it with.

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)

output

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
1
votes

you need to return it otherwhise your modification stay in the local scope of the funtion..

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

then

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