- 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 good triplets in Python

Suppose we have an array nums, and three different integers a, b and c. We have to find the number of good triplets. A triplet (nums[i], nums[j], nums[k]) is said to be a good triplet if the following conditions are true −

0 <= i < j < k < number of elements in nums

|nums[i] - nums[j]| <= a

|nums[j] - nums[k]| <= b

|nums[i] - nums[k]| <= c

We have to count the number of good triplets.

So, if the input is like nums= [5,2,3,3,12,9], a = 7, b = 2, c = 3, then the output will be 4 because the good triplets are [(5,2,3), (5,2,3), (5,3,3), (2,3,3)]

To solve this, we will follow these steps −

res := 0

for i in range 0 to size of nums - 1, do

for j in range i+1 to size of nums - 1, do

for k in range j+1 to size of nums - 1, do

if |nums[i] - nums[j]| <= a and |nums[j] - nums[k]| <= b and |nums[i] - nums[k]| <= c, then

res := res + 1

return res

## Example (Python)

Let us see the following implementation to get better understanding −

def solve(nums, a, b, c): res = 0 for i in range(len(nums)): for j in range(i+1, len(nums)): for k in range(j+1, len(nums)): if abs(nums[i] - nums[j]) <= a and abs(nums[j] - nums[k]) <= b and abs(nums[i] - nums[k]) <= c: res += 1 return res nums= [5,2,3,3,12,9] a = 7 b = 2 c = 3 print(solve(nums, a, b, c))

## Input

[5,2,3,3,12,9], 7, 2 3

## Output

4

- Related Articles
- Program to find number of good pairs in Python
- Program to find number of good leaf nodes pairs using Python
- Program to find number of good ways to split a string using Python
- Program to count number of valid triangle triplets in C++
- Program to find maximum score of a good subarray in Python
- Python Program to Determine all Pythagorean Triplets in the Range
- Program to find a good string from a given string in Python
- Program to check we can get a digit pair and any number of digit triplets or not in Python
- Program to check number of triplets from an array whose sum is less than target or not Python
- Program to find minimum amount needed to be paid all good performers in Python
- Python program to find list of triplets for which i+j+k is not same as n
- Program to find number of distinct subsequences in Python
- Program to find number of squareful arrays in Python
- Count number of triplets with product equal to given number in C++
- How to find the 3 Pythagorean triplets with only one number?