-1

In the following code, I need to return b so that I can use it in another function. I tried testing to see if b would be returned but when I run def main and print(n_boxes), it gives me None. However if I changed return b to print(b) and print(n_boxes) to n-boxes, I get the correct output.

  def subsets(a, b, lo):
    hi = len(a)
    subs_2 = []
    if (lo == hi):
      return b
    else:
      c = b[:]
      b.append(a[lo])
      subsets (a, c, lo + 1)
      subsets (a, b, lo + 1)
  def main():
    boxes = [[1, 2, 3], [4, 5,6], [6, 6, 9], [3, 8, 4]]
    b = []
    n_boxes = subsets(boxes, b, 0)
    print(n_boxes)
  main()

I am not sure what I am doing wrong. I need the values for b. Thanks!

Ok so I want all possible subsets to be returned. The "def subsets" can do that. With "print b" my output is

[]
[[3, 8, 4]]
[[6, 6, 9]]
[[6, 6, 9], [3, 8, 4]]
[[4, 5, 6]]
[[4, 5, 6], [3, 8, 4]]
[[4, 5, 6], [6, 6, 9]]
[[4, 5, 6], [6, 6, 9], [3, 8, 4]]
[[1, 2, 3]]
[[1, 2, 3], [3, 8, 4]]
[[1, 2, 3], [6, 6, 9]]
[[1, 2, 3], [6, 6, 9], [3, 8, 4]]
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6], [3, 8, 4]]
[[1, 2, 3], [4, 5, 6], [6, 6, 9]]
[[1, 2, 3], [4, 5, 6], [6, 6, 9], [3, 8, 4]]

I want to be able to use the above subsets individually. So I am trying to find a way to return the subsets and be able to write a function that will give me subsets of length two. To clarify, I would be able to write such a function, but I would need the individual subsets first.

1
  • can you add the outputs you got?
    – venpa
    Mar 1, 2014 at 18:19

1 Answer 1

0

You are calling subsets recursively, but don't return anything in the else: branch.

For the if (lo == hi): branch you return b, but if lo != hi you don't return anything at all and thus the return value is None, the default. If you wanted something returned for that branch, you need to add a return statement there too.

Because b is altered in-place, perhaps you just wanted to print b? You don't need to return anything either in that case:

def subsets(a, b, lo):
    hi = len(a)
    subs_2 = []
    if lo != hi:
        c = b[:]
        b.append(a[lo])
        subsets (a, c, lo + 1)
        subsets (a, b, lo + 1)

def main():
    boxes = [[1, 2, 3], [4, 5,6], [6, 6, 9], [3, 8, 4]]
    b = []
    subsets(boxes, b, 0)
    print(b)

main()

Note that the code ignores subs_2 entirely, you could just as well remove that line. c is also ignored, as altered by the recursive call, is also ignored. The above code copies all sublists in boxes unaltered to b.

I suspect you wanted a different outcome, but you didn't give us any indication as to what the code is supposed to do.

1
  • In the function subsets, I am trying get all possible outputs. Mar 1, 2014 at 21:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.