0

If I try the following snippets of code on a binary tree, and try to print the arr and string later, arr gives me the correct result but string is empty. Any thoughts? Is it something to do with lists being passed by reference and strings passed by value?

def post_order(root, arr = []):
    if(root is not None):
        post_order(root.left, arr)
        post_order(root.right, arr)
        arr.append(root.value)

def post_order1(root, string = ''):
    if(root is not None):
        post_order1(root.left, string)
        post_order1(root.right, string)
        string += str(root.value)

# assume I've made my binary tree
arr, string = [], ''
post_order(root, arr)
post_order1(root, string)
print arr, string
# arr holds the correct post-order sequence
# string is empty
Danny Liu
  • 499
  • 2
  • 5
  • 12
  • strings are immutable so `string += str(root.value)` might not be doing much, do you mean to += before you call post_order1 passing the new string and then returning it? I think you may fare better with a class making string an attribute – Padraic Cunningham Apr 25 '16 at 19:34
  • 1
    Related: [In Python, why can a function modify some arguments as perceived by the caller, but not others?](http://stackoverflow.com/q/575196/4279) – jfs Apr 25 '16 at 19:37
  • You're not including sufficient information. Include you inputs, desired and existing outputs. Also, you should really return those functions so that the variables are garbage collected. – Pouria Apr 25 '16 at 19:40

3 Answers3

2

In Python, lists are mutable and strings are immutable. This means that a list can be modified, but a string cannot. Strings can only be reassigned.

In your function, you are modifying the list using .append(), but you are only reassigning your string +=

Brian
  • 1,659
  • 12
  • 17
1

Arr is an array, which you extend. String passed to post_order1 is an immutable object and a copy is created when updated. As a result, the original string stays unchanged.

kofemann
  • 4,217
  • 1
  • 34
  • 39
-1

You should rectify your code like this:

def post_order1(root, string = ''):
    if not root : return string

left  = post_order1(root.left, string)
right = post_order1(root.right, left)
return right + str(root.value)
nino_701
  • 672
  • 3
  • 13