Subsets in Python

PythonServer Side ProgrammingProgramming

Suppose we have a set of numbers; we have to generate all possible subsets of that set. This is also known as power set. So if the set is like [1,2,3], then the power set will be [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]

Let us see the steps −

  • We will solve this using recursive approach. So if the recursive method name is called solve(), and this takes the set of numbers (nums), temporary set (temp), res and index
  • The solve() function will work like below −
  • if index = length of nums, then create a list same as temp, and insert into res and return
  • temp[index] := 0
  • solve(nums, temp, res, index + 1)
  • temp[index] := 1
  • solve(nums, temp, res, index + 1)
  • The main function will be like below −
  • res := an empty list
  • create temp list of size same as the nums, and fill this with 0
  • call solve(nums, temp, res, 0)
  • main_res := an empty list
  • for all lists in temp_res
    • temp := empty list
    • for i := 0 to length of lists
      • if lists[i] = 1, then insert nums[i] into temp
    • insert temp into main_res
  • return main res

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def subsets(self, nums):
      temp_result = []
      self.subsets_util(nums,[0 for i in range(len(nums))],temp_result,0)
      main_result = []
      for lists in temp_result:
         temp = []
         for i in range(len(lists)):
            if lists[i] == 1:
               temp.append(nums[i])
         main_result.append(temp)
      return main_result
   def subsets_util(self,nums,temp,result,index):
      if index == len(nums):
         result.append([i for i in temp])
         #print(temp)
         return
      temp[index] = 0
      self.subsets_util(nums,temp,result,index+1)
      temp[index] = 1
      self.subsets_util(nums, temp, result,index + 1)
ob1 = Solution()
print(ob1.subsets([1,2,3,4]))

Input

[1,2,3,4]

Output

[[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], 
[1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]]
raja
Published on 03-Feb-2020 14:36:56
Advertisements