

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Questions & Answers
- Python program to get all subsets having sum s\n
- Python program to get all subsets of given size of a set
- Python program to get all subsets of a given size of a set
- Program to count subsets that sum up to k in python
- Python - Get sum of tuples having same first value
- Sum of XOR of all possible subsets in C++
- Python Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers
- Sum of the products of all possible Subsets in C++
- Count subsets having distinct even numbers in C++
- Java Program To Find all the Subsets of a String
- Count all sub-arrays having sum divisible by k
- Subsets in Python
- Partition to K Equal Sum Subsets in C++
- Get all the tables from a MySQL database having a specific column, let’s say xyz?
- Sum of all subsets of a set formed by first n natural numbers
- Program to find sum of the sum of all contiguous sublists in Python