- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 sn
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 Articles
- 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 Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers
- Sum of all subsets of a set formed by first n natural numbers
- Sum of XOR of all possible subsets in C++
- Python - Get sum of tuples having same first value
- Printing all subsets of {1,2,3,…n} without using array or loop in C program
- List all the subsets of a set {m , n}
- Sum of the products of all possible Subsets in C++
- Java Program To Find all the Subsets of a String
- Program to find sum of concatenated pairs of all each element in a list in Python?\n
- Program to find sum of the costs of all simple undirected graphs with n nodes in Python
- Count subsets having distinct even numbers in C++
- Python Program to Get K initial powers of N
