
- 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 find number of sublists whose sum is given target in python
Suppose we have a list of numbers called nums and another value target, we have to find the number of sublists whose sum is same as target.
So, if the input is like nums = [3, 0, 3] target = 3, then the output will be 4, as we have these sublists whose sum is 3: [3], [3, 0], [0, 3], [3].
To solve this, we will follow these steps:
- temp := an empty map
- temp[0] := 1
- s := 0
- ans := 0
- for i in range 0 to size of nums, do
- s := s + nums[i]
- comp := s - target
- if comp is in temp, then
- ans := ans + temp[comp]
- temp[s] := temp[s] + 1
- return ans
Let us see the following implementation to get better understanding:
Example Code
from collections import defaultdict class Solution: def solve(self, nums, target): temp = defaultdict(int) temp[0] = 1 s = 0 ans = 0 for i in range(len(nums)): s += nums[i] comp = s - target if comp in temp: ans += temp[comp] temp[s] += 1 return ans ob = Solution() nums = [3, 0, 3] target = 3 print(ob.solve(nums, target))
Input
[3, 0, 3], 3
Output
4
- Related Articles
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to find the sum of the lengths of two nonoverlapping sublists whose sum is given in Python
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Program to find size of smallest sublist whose sum at least target in Python
- Program to find minimum number of subsequence whose concatenation is same as target in python
- Program to find lowest sum of pairs greater than given target in Python
- Program to find product of few numbers whose sum is given in Python
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find number of sublists with sum k in a binary list in Python
- Program to find number of given operations required to reach Target in Python
- Program to find number of distinct quadruple that forms target sum in python
- Program to check number of triplets from an array whose sum is less than target or not Python
- Program to find number of sublists we can partition so given list is sorted finally in python
- C++ Program to find Number Whose XOR Sum with Given Array is a Given Number k
- Program to find maximum sum of two non-overlapping sublists in Python

Advertisements