
- 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 with sum k in a binary list in Python
Suppose we have a binary list with 0s or 1s. We also have another input called k, we have to find the number of sublists whose sum is same as k.
So, if the input is like nums = [1, 0, 0, 1, 1, 1, 0, 1] k = 3, then the output will be 8 because the sublists are [1,0,0,1,1], [0,0,1,1,1], [0,0,1,1,1,0], [0,1,1,1], [0,1,1,1,0], [1,1,1], [1,1,1,0] [1,1,0,1].
To solve this, we will follow these steps −
- sums := a map initially contains valye 1 for key 0
- r_sum := 0
- ans := 0
- for each x in nums, do
- r_sum := r_sum + x
- ans := ans + (sums[r_sum - k] if (r_sum - k) is present, otherwise 0)
- sums[r_sum] := 1 + (sums[r_sum - k] if (r_sum - k) is present, otherwise 0)
- return ans
Example
Let us see the following implementation to get better understanding −
def solve(nums, k): sums = {0: 1} r_sum = 0 ans = 0 for x in nums: r_sum += x ans += sums.get(r_sum - k, 0) sums[r_sum] = sums.get(r_sum, 0) + 1 return ans nums = [1, 0, 0, 1, 1, 1, 0, 1] k = 3 print(solve(nums, k))
Input
[1, 0, 0, 1, 1, 1, 0, 1], 3
Output
8
- Related Articles
- Program to count number of sublists with exactly k unique elements in Python
- Program to find minimum largest sum of k sublists in C++
- Program to find number of sublists whose sum is given target in python
- Program to find number of sublists that contains exactly k different words in Python
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Program to find max values of sublists of size k in Python
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find max number of K-sum pairs in Python
- Program to find maximum sum of two non-overlapping sublists in Python
- Program to find k sublists with largest sums and return sums in ascending order in Python
- Python program to find the group sum till each K in a list
- Program to find largest sum of 3 non-overlapping sublists of same sum in Python
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Python program to print all sublists of a list.
- Program to find number of sublists we can partition so given list is sorted finally in python

Advertisements