0

Why in the step list(subset[I]) is required? If I do not put list() I get a wrong answer. The question is regarding finding subsets from a unique list like [1,2,3] the answer should be [],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3] The code below is the correct answer -- but I am just confused why the list() is required in the code. Running without that gives a completely different answer.

def subsets(nums):
    subset = []
    subset.append([])
    for num in nums:
        for i in range(len(subset)):
            new_list = list(subset[i])
            new_list.append(num)
            subset.append(new_list)
    return subset
Rad
  • 7
  • 6
  • 1
    list(subset[i]) will create a new copy of the sublist subset[i] which is used to add to new element, if you dont do that then data will added to old list subset[i] and different result will come – sahasrara62 Jul 10 '20 at 16:53

1 Answers1

-1

You can get the combinations of a list by using itertools.combinations:

import itertools

stuff = [1, 2, 3, 4, 5]
all_combinations = []
for L in range(0, len(stuff)+1):
    for combination in itertools.combinations(stuff, L):
        all_combinations.append(combination)

all_combinations = list(all_combinations)

You can filter out duplicates of a list by constructing a set from the list:

unique_combinations = set(all_combinations)

Even better, you can use the powerset recipe from the itertools documentation, with a slight modification on Line 3:

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(set(iterable)) # we use set to enforce uniqueness
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
zr0gravity7
  • 2,917
  • 1
  • 12
  • 33