0

I wrote this code to try to get the powerset of a python list, and return it as a list of lists, but for some reason it is not working, because it gives a 'NoneType' object has no attribute 'append'. I cannot figure out why though, can anyone help?

def subsetHelper(current_subset, result, nums):
    if not nums:
        result.append(current_subset)
    else:
        subsetHelper(current_subset.append(nums[0]), result, nums[1:])
        subsetHelper(current_subset, result, nums[1:])

def subsets(nums):
    result = []
    subsetHelper([], result, nums)

    print nums
Kamal
  • 560
  • 1
  • 5
  • 14
  • 1
    `list.append` returns `None`. You don't want to do `subsetHelper(current_subset.append(nums[0]), ...` – Vincent Savard Mar 07 '16 at 19:50
  • 1
    Also, you might want to look at `itertools` for this purpose. `powerset = itertools.chain.from_iterable(itertools.combinations(nums, i) for i in range(len(nums)+1))` would do the work (it would return a generator to iterate over; if the result is small enough you could wrap in `list` to create the complete `list` of subsets). – ShadowRanger Mar 07 '16 at 19:58
  • Ah ok, thanks. this is an interview question so i dont think i can use itertools – Kamal Mar 07 '16 at 20:22

0 Answers0