- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- Program to find minimum largest sum of k sublists in C++
- Program to count number of sublists with exactly k unique elements in Python
- 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 largest sum of 3 non-overlapping sublists of same sum in Python
- Python program to print all sublists of a list.
- Python program to find the group sum till each K in a list
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to find number of distinct combinations that sum up to k in python

Advertisements