Coding Problem 13
Find subsets
asked by Facebook
Ques. Given a list of given numbers return all the possible subsets of those numbers. For example - if given numbers are [1, 2] then its subsets are [None], [1], [2], [1, 2]. Total number of subsets can be found as 2^n where n is number of items given in the list.
Solution.
We know the length of given list and number of subsets are the (2^n). What we can do is that we can make lists equal to (2^n) and length of each list will be equal to n. Now in the list we can initially set each value to 0 and for each element we traverse in the input list one time we can set the value at index equal to current element index set to current element and another time we can set it to None. In short it can be understood as for each element one time we will include it and next time we will not include it and set that index value to None.
Lets see the code -
def all_subsets(input_list):
subsets = [0]*len(input_list)
helper(input_list, subsets, 0)
def helper(input_list, subsets, i):
if i==len(input_list):
print(subsets)
else:
subsets[i]=None
helper(input_list, subsets, i+1)
subsets[i]=input_list[i]
helper(input_list, subsets, i+1)
all_subsets([1, 2])
Output: [none, none]
[none, 2]
[1, none]
[1, 2]

Comments
Post a Comment