Find all triplets in a list with given sum in Python

PythonServer Side ProgrammingProgramming

In a list of numbers we want to find out which three elements can join to give a certain sum. We call it a triplet. And in the list there can be many such triplets. For example, the sum 10 can be generated form numbers 1,6,3 as well as 1,5,4. In this article we will see how to find out all such triplets from a given list of numbers.

Using range and temp variables

This is the traditional approach in which we will create temporary variables. These variables will hold the elements from the list and check if their sum is equating to the required value. Then it will keep accumulating such variables into the final result set.

Example

 Live Demo

def SumTriplets(listA, sum):
   trpltcnt = 0
   res = []

   for i in range(0, len(listA) - 1):

      s = set()
      tmp = []

      # Adding first element
      tmp.append(listA[i])

      current_sum = sum - listA[i]

      for j in range(i + 1, len(listA)):

         if (current_sum - listA[j]) in s:
            trpltcnt += 1

            # Adding second element
            tmp.append(listA[j])

            # Adding third element
            tmp.append(current_sum - listA[j])

            # Appending tuple to the final list
            res.append(tuple(tmp))
            tmp.pop(2)
            tmp.pop(1)
         s.add(listA[j])

   return res


listA = [11,12,13,14,15,16,17,18,19,20]

print("Required triplets:\n",SumTriplets(listA, 40))

Output

Running the above code gives us the following result −

Required triplets:
[(11, 15, 14), (11, 16, 13), (11, 17, 12), (12, 15, 13)]

Example

 Live Demo

from itertools import combinations

listA = [11,12,13,14,15,16,17,18,19,20]

def fsum(val):
      return sum(val) == 40

res = list(filter(fsum,list(combinations(listA, 3))))

print("Required triplets:\n",res)

Output

Running the above code gives us the following result −

Required triplets:
[(11, 12, 17), (11, 13, 16), (11, 14, 15), (12, 13, 15)]
raja
Published on 26-Aug-2020 07:36:38
Advertisements