
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program for Subset Sum Problem
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a set of non-negative integers in an array, and a value sum, we need to determine if there exists a subset of the given set with a sum equal to a given sum.
Now let’s observe the solution in the implementation below −
# Naive approach
Example
def SubsetSum(set, n, sum) : # Base Cases if (sum == 0) : return True if (n == 0 and sum != 0) : return False # ignore if last element is > sum if (set[n - 1] > sum) : return SubsetSum(set, n - 1, sum); # else,we check the sum # (1) including the last element # (2) excluding the last element return SubsetSum(set, n-1, sum) or SubsetSum(set, n-1, sumset[n-1]) # main set = [2, 14, 6, 22, 4, 8] sum = 10 n = len(set) if (SubsetSum(set, n, sum) == True) : print("Found a subset with given sum") else : print("No subset with given sum")
Output
Found a subset with given sum
# dynamic approach
Example
# maximum number of activities that can be performed by a single person def Activities(s, f ): n = len(f) print ("The selected activities are:") # The first activity is always selected i = 0 print (i,end=" ") # For rest of the activities for j in range(n): # if start time is greater than or equal to that of previous activity if s[j] >= f[i]: print (j,end=" ") i = j # main s = [1, 2, 0, 3, 2, 4] f = [2, 5, 4, 6, 8, 8] Activities(s, f)
Output
Found a subset with given sum
Conclusion
In this article, we have learned about how we can make a Python Program for Subset Sum Problem
- Related Articles
- Subset Sum Problem
- C / C++ Program for Subset Sum (Backtracking)
- Python Program for Activity Selection Problem
- Python Program for 0-1 Knapsack Problem
- Python Program for Number of stopping station problem
- C Program for Activity Selection Problem
- C Program for Number of stopping station problem
- C++ program to choose some numbers for which there will be no subset whose sum is k
- Combination sum problem using JavaScript
- Partition Equal Subset Sum in C++
- Sum of subset differences in C++
- Subset with maximum sum in JavaScript
- Program to implement the fractional knapsack problem in Python
- C++ Program to Solve Travelling Salesman Problem for Unweighted Graph
- Python Program for cube sum of first n natural numbers

Advertisements