- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 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
Advertisements