1

I'm trying to wrap my head around the concept of recursion and has the following queries with regard to the output of the below code:

def subsetsofSet(input_list, set_list=None):
    print "IN input_list: {0}".format(input_list)
    if not input_list:
        return

    input_list.pop()

    subsetsofSet(input_list)
    print "RETURN input_list: {0}".format(input_list)

subsetsofSet([1,2,3])

Output is as below:

IN input_list: [1, 2, 3]
IN input_list: [1, 2]
IN input_list: [1]
IN input_list: []
RETURN input_list: []
RETURN input_list: []
RETURN input_list: []

Why is the RETURN input_list always empty? Shouldn't it be displayed in the reverse manner of the IN input_list? Appreciate any help in understanding this?

8
  • 1
    You need to return subsetsofSet(input_list) Commented Nov 30, 2015 at 7:08
  • could you add the expected output to be and is your indentation right ? Commented Nov 30, 2015 at 7:10
  • i was expecting the output to be as below IN input_list: [1, 2, 3] IN input_list: [1, 2] IN input_list: [1] IN input_list: [] RETURN input_list: [1] RETURN input_list: [1,2] RETURN input_list: [1,2,3] Commented Nov 30, 2015 at 7:14
  • @thefourtheye That would be true if they were actually using the return value of the function anywhere; it doesn't look like they are. Commented Nov 30, 2015 at 7:20
  • @OP The RETURN input_list is always empty because you recursively pop all elements from the list before any of the function calls end. Commented Nov 30, 2015 at 7:20

1 Answer 1

1

A list is a mutable element, so you only pass a reference to the original list and it is popped on each call. If you printed the id of the list, you could see the same value.

So even if before calling subsetsofSet(input_list) for the second time the list was [1,2] after the return it is empty.

You should pass a copy of the list if you do not want it to be changed by recursive calls:

def subsetsofSet(input_list, set_list=None):
    print "IN input_list: {0}".format(input_list)
    if not input_list:
        return

    input_list.pop()

    subsetsofSet(input_list[:])
    print "RETURN input_list: {0}".format(input_list)

subsetsofSet([1,2,3])

Output is then:

IN input_list: [1, 2, 3]
IN input_list: [1, 2]
IN input_list: [1]
IN input_list: []
RETURN input_list: []
RETURN input_list: [1]
RETURN input_list: [1, 2]
Sign up to request clarification or add additional context in comments.

Comments

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.