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
3
  • 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 Commented Apr 25, 2016 at 19:34
  • 1
    Related: In Python, why can a function modify some arguments as perceived by the caller, but not others? Commented Apr 25, 2016 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. Commented Apr 25, 2016 at 19:40

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh that makes a lot of sense! Thanks Brian :)
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.

Comments

-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)

1 Comment

I corrected the code in the post. Thank you @Danny Liu

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.