
- 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
Program to count subsets that sum up to k in python
Suppose we have a list of numbers called nums and another value k, we have to find the number of subsets in the list that sum up to k. If the answer is very large then mod this with 10^9 + 7
So, if the input is like nums = [2, 3, 4, 5, 7] k = 7, then the output will be 3, as We can choose the subsets [2,5],[3,4] and [7].
To solve this, we will follow these steps −
- dp := a list of size (k + 1) and fill with 0
- dp[0] := 1
- m := 10^9 + 7
- for i in range 0 to size of nums - 1, do
- for j in range k down to 0, decrease by 1, do
- if nums[i] <= j, then
- dp[j] := dp[j] + dp[j - nums[i]]
- dp[j] := dp[j] mod m
- if nums[i] <= j, then
- for j in range k down to 0, decrease by 1, do
- return dp[k] mod m
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, k): dp = [0] * (k + 1) dp[0] = 1 m = int(1e9 + 7) for i in range(len(nums)): for j in range(k, -1, -1): if nums[i] <= j: dp[j] += dp[j - nums[i]] dp[j] %= m return dp[k] % m ob = Solution() nums = [2, 3, 4, 5, 7] k = 7 print(ob.solve(nums, k))
Input
[2, 3, 4, 5, 7], 7
Output
3
- Related Articles
- Program to find number of distinct combinations that sum up to k in python
- Program to count non-empty subsets where sum of min and max element of set is less than k in Python
- Partition to K Equal Sum Subsets in C++
- Program to count number of paths whose sum is k in python
- Python program to get all subsets having sum s\n
- Program to find any two numbers in a list that sums up to k in Python
- Count subtrees that sum up to a given value x in C++
- Count number of ways to partition a set into k subsets in C++
- Program to check sum of two numbers is up to k from sorted List or not in Python
- Program to Find K-Largest Sum Pairs in Python
- C++ program to count number of minimum coins needed to get sum k
- Program to count k length substring that occurs more than once in the given string in Python
- Program to find sum of rectangle whose sum at most k in Python
- Count subsets that satisfy the given condition in C++
- Program to find the sum of largest K sublist in Python

Advertisements