- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 distinct quadruple that forms target sum in python
Suppose we have four lists of numbers A, B, C, and D, and also have a target value, we have to find the number of distinct quadruple (i, j, k, l) such that A[i] + B[j] + C[k] + D[l] is same as target.
So, if the input is like A = [5, 4, 3] B = [8, 4] C = [6, 2] D = [4, 10] target = 23, then the output will be 3, the quadruples are [5, 8, 6, 4] [3, 4, 6, 10] [3, 8, 2, 10].
To solve this, we will follow these steps:
- count := 0
- m := an empty map
- for each i in A, do
- for each j in B, do
- m[i + j] := m[i + j] + 1
- for each k in C, do
- for each z in D, do
- if (target - (k + z)) is in m, then
- count := count + m[target - (k + z)]
- if (target - (k + z)) is in m, then
- for each z in D, do
- for each j in B, do
- return count
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, A, B, C, D, target): count = 0 from collections import defaultdict from collections import Counter m = defaultdict(int) for i in A: for j in B: m[i + j] += 1 for k in C: for z in D: if target - (k + z) in m: count += m[target - (k + z)] return count ob = Solution() A = [5, 4, 3] B = [8, 4] C = [6, 2] D = [4, 10] target = 23 print(ob.solve(A, B, C, D, target))
Input
[5, 4, 3], [8, 4], [6, 2], [4, 10], 23
Output
3
- Related Articles
- Program to find number of distinct combinations that sum up to k in python
- Program to find number of sublists whose sum is given target in python
- Number of Submatrices That Sum to Target in C++
- Program to find number of distinct subsequences in Python
- Program to find maximum number of non-overlapping subarrays with sum equals target using Python
- Program to count maximum number of distinct pairs whose differences are larger than target in Python
- Program to find the sum of elements that forms a Z shape on matrix in Python
- Program to find lowest sum of pairs greater than given target in Python
- Program to find number of combinations of coins to reach target in Python
- Program to find number of given operations required to reach Target in Python
- Number of Dice Rolls With Target Sum in Python
- Program to find size of smallest sublist whose sum at least target in Python
- Program to find minimum element addition needed to get target sum in Python
- Program to find minimum number of buses required to reach final target in python
- Program to find sum of two numbers which are less than the target in Python

Advertisements