Change language

# Python | Find all triples in a list with a given sum

| |

Examples :

`  Input:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 10  Output:  [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)]  Input:  [12, 3, 6, 1, 6, 9], k = 24  Output:  [(12, 6, 6), (12, 9, 3)] `

Approach # 1: Naive (Using a set)
In this approach, we use two for loops. The first loop sets the first element, the other checks if the other two elements, including the first one, add up to k or not. This approach requires O (n 2 ) time complexity.

 ` # Python3 program for finding total ` ` Number of triplets in the list of temporary variables with a given k value `   ` def ` ` findTriplets (lst, k): ` ` triplet_count ` ` = ` ` 0 ` ` final_temp_list ` ` = ` ` [] ` ` `  ` ` ` for ` ` i ` ` in ` ` range ` ` (` ` 0 ` `, ` ` len ` ` (lst) ` ` - ` ` 1 ` `): `   ` ` ` s ` ` = ` ` set ` ` () ` ` temp_list ` ` = ` ` [] ` ` `  ` # Add first element ` ` temp_list.append (lst [i]) `   ` ` ` curr_k = k - lst [i] ``   for j in range (i + 1 , len (lst)):    if (curr_k - lst [j]) in s:  triplet_count + = 1   # Add second element temp_list.append (lst [j])   # Adding a third element temp_list.append (curr_k - lst [j])   # Add a tuple to the final list final_temp_list.append ( tuple (temp_list)) temp_list.pop ( 2 ) temp_list.pop ( 1 )   s.add (lst [j])    return final_temp_list   Driver code lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] k = 10 print (findTriplets (lst, k)) `

Exit:

` [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)] `

Approach # 2 Using itertools
Python’s itertools module provides combined (iterable, r) function. This tool returns subsequences of length r elements from iterative input. Each time we make a combination of 3 elements and check if they add up to k or not.

 ` # Python3 program for finding total ` ` Number of triplets in the list with the given amount ` ` from ` ` itertools ` ` import ` ` combinations `   ` def ` ` findTriplets (lst, key): `   ` def ` ` valid (val): ` ` return ` ` sum ` ` (val) ` ` = = key ``   return list ( filter (valid, list (combinations (lst, 3 ))))   Driver code lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] print (findTriplets (lst, 10 )) `

Output:

` [(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)] `

## Shop

Learn programming in R: courses

\$

Best Python online courses for 2022

\$

Best laptop for Fortnite

\$

Best laptop for Excel

\$

Best laptop for Solidworks

\$

Best laptop for Roblox

\$

Best computer for crypto mining

\$

Best laptop for Sims 4

\$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

NUMPYNUMPY

How to specify multiple return types using type-hints

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

NUMPYNUMPY

glob exclude pattern

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

NUMPYNUMPY

Python CSV error: line contains NULL byte

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

## Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries