Python program to get all subsets having sum s


When it is required to get all the subset having a specific sum ‘s’, a method is defined that iterates through the list and gets all combinations of the list, and if it matches the sum, it is printed on the console.

Example

Below is a demonstration of the same

from itertools import combinations

def sub_set_sum(size, my_array, sub_set_sum):

   for i in range(size+1):
      for my_sub_set in combinations(my_array, i):

         if sum(my_sub_set) == sub_set_sum:
            print(list(my_sub_set))

my_size = 6
my_list = [21, 32, 56, 78, 45, 99, 0]
print("The list is :")
print(my_list)
subset_sum = 53
print("The result is :")
sub_set_sum(my_size, my_list, subset_sum)

Output

The list is :
[21, 32, 56, 78, 45, 99, 0]
The result is :
[21, 32]
[21, 32, 0]

Explanation

  • The required packages are imported into the environment.

  • A method named ‘sub_set_sum’ is defined that takes the size of the list, the list as parameters.

  • It iterates through the list and uses the ‘combinations’ method to get all combinations.

  • If the sum is same as a specific value, it is converted to a list and displayed on the console.

  • Outside the method, a size is defined.

  • A list is defined and is displayed on the console.

  • A subset value is defined.

  • The method is called by passing the required parameter.

  • The output is displayed on the console.

Updated on: 21-Sep-2021

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements