Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to get all subsets having sum s
When working with lists, you might need to find all subsets that sum to a specific value. Python's itertools.combinations provides an efficient way to generate all possible subsets and check their sums.
Using itertools.combinations
The combinations function generates all possible subsets of different sizes from the input list ?
from itertools import combinations
def find_subsets_with_sum(arr, target_sum):
result = []
# Generate subsets of all possible sizes (0 to len(arr))
for size in range(len(arr) + 1):
for subset in combinations(arr, size):
if sum(subset) == target_sum:
result.append(list(subset))
return result
# Example usage
numbers = [21, 32, 56, 78, 45, 99, 0]
target = 53
print("Original list:", numbers)
print("Target sum:", target)
print("Subsets with sum", target, ":")
subsets = find_subsets_with_sum(numbers, target)
for subset in subsets:
print(subset)
Original list: [21, 32, 56, 78, 45, 99, 0] Target sum: 53 Subsets with sum 53 : [21, 32] [21, 32, 0]
How It Works
The algorithm works in these steps:
- Generate combinations: For each possible subset size (0 to n), generate all combinations
- Check sum: Calculate the sum of each subset
- Match target: If the sum equals the target, add it to results
Alternative Implementation with Generator
For memory efficiency with large datasets, you can use a generator approach ?
from itertools import combinations
def subsets_with_sum_generator(arr, target_sum):
"""Generator that yields subsets with target sum"""
for size in range(len(arr) + 1):
for subset in combinations(arr, size):
if sum(subset) == target_sum:
yield list(subset)
# Example usage
numbers = [10, 20, 30, 40]
target = 50
print("Finding subsets with sum", target)
for subset in subsets_with_sum_generator(numbers, target):
print(subset)
Finding subsets with sum 50 [10, 40] [20, 30]
Performance Considerations
| Aspect | List Approach | Generator Approach |
|---|---|---|
| Memory Usage | Higher (stores all results) | Lower (yields one at a time) |
| Processing Speed | Faster for small datasets | More efficient for large datasets |
| Best Use Case | Small lists, need all results | Large lists, process incrementally |
Conclusion
Use itertools.combinations to find all subsets with a target sum efficiently. The generator approach is memory-friendly for large datasets, while the list approach is simpler for smaller problems.
Advertisements
