Open In App

Python – Construct Sum pairs equal to K

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we can have problem in which we need to extract pairs which have sum equal to K. This kind of problem is common and can have application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : 
test_list = [1, 9, 5, 5, 7]
K = 10
Output : [(1, 9), (5, 5)]

Input : 
test_list = [1, 9, 7, 8, 3]
K = 12
Output : [(9, 3)]

Method #1 : Using list comprehension + sum() The combination of above functions can be used to solve this problem. In this, we perform the task of finding summation equal to K using sum() and list comprehension is used to logic and pair building. 

Python3




# Python3 code to demonstrate working of
# Construct Sum pairs equal to K
# Using list comprehension + sum()
 
# initializing list
test_list = [3, 4, 0, 5, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 7
 
# Construct Sum pairs equal to K
# Using list comprehension + sum()
res = [(test_list[idx], test_list[j]) for idx in range(len(test_list))
                               for j in range(idx + 1, len(test_list))
                          if sum((test_list[idx], test_list[j])) == K]
 
# printing result
print("The paired tuples equal to K  : " + str(res))


Output : 

The original list is : [3, 4, 0, 5, 2]
The paired tuples equal to K  : [(3, 4), (5, 2)]

Time Complexity: O(n) where n is the number of elements in the list “test_list”.  list comprehension + sum() performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list

Method #2: Using combinations() + sum() The combination of above functions can be used to solve this problem. In this combination() is used to form pairs equal to K. 

Python3




# Python3 code to demonstrate working of
# Construct Sum pairs equal to K
# Using combinations() + sum()
from itertools import combinations
 
# initializing list
test_list = [3, 4, 0, 5, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 7
 
# Construct Sum pairs equal to K
# Using combinations() + sum()
res = [ele for ele in combinations(test_list, 2) if sum(ele) == K]
 
# printing result
print("The paired tuples equal to K  : " + str(res))


Output : 

The original list is : [3, 4, 0, 5, 2]
The paired tuples equal to K  : [(3, 4), (5, 2)]

 Method #3: Using dictionary

Python3




# Define a function named "find_pairs" that takes two arguments:
#   - test_list: a list of integers
#   - K: an integer representing the target sum of pairs
def find_pairs(test_list, K):
    # Create an empty list to hold the resulting pairs
    result = []
    # Create an empty dictionary to keep track of seen numbers
    seen = {}
    # Iterate over each number in the input list
    for num in test_list:
        # Calculate the difference between the target sum and the current number
        diff = K - num
        # Check if the difference is already in the seen dictionary
        if diff in seen:
            # If so, add a tuple of the current number and the difference to the result list
            result.append((diff, num))
        # Add the current number to the seen dictionary
        seen[num] = True
    # Return the resulting pairs list
    return result
 
# Create a test list of integers
test_list = [1, 9, 5, 5, 7]
# Define the target sum of pairs
K = 10
# Call the "find_pairs" function with the test list and target sum as arguments,
# and print the resulting pairs list
print(find_pairs(test_list, K))


Output

[(1, 9), (5, 5)]

Time complexity: O(n)
Auxiliary space: O(min(n, K)). 

 Method #4: Using recursion:

  1. Define a function named “find_pairs” that takes two arguments: test_list and K
  2. Initialize an empty list named “result” to hold the resulting pairs
  3. Check if the length of the test list is less than 2. If so, return the empty result list
  4. Take the first element of the test list and assign it to a variable named “first_num”
  5. Create a new list named “rest_list” by slicing the original list from the second element to the end
    Iterate over each element in the rest_list and check if the difference between K and the first_num is equal to the current element
  6. If it is, append a tuple of the first_num and the current element to the result list
  7. Recursively call the “find_pairs” function with the rest_list as the new test list
  8. Add the resulting pairs list from the recursive call to the result list
  9. Return the resulting pairs list

Python3




def find_pairs(test_list, K):
    # Initialize an empty list to hold the resulting pairs
    result = []
    # Base case: if the length of the test list is less than 2, return the empty result list
    if len(test_list) < 2:
        return result
    # Recursive case:
    # - take the first element of the test list
    # - find all elements in the rest of the list that add up to K minus the first element
    # - add each pair of elements to the result list
    # - recursively call the function with the rest of the list as the new test list
    else:
        first_num = test_list[0]
        rest_list = test_list[1:]
        for num in rest_list:
            if num == K - first_num:
                result.append((first_num, num))
        result += find_pairs(rest_list, K)
    # Return the resulting pairs list
    return result
  # Create a test list of integers
test_list = [1, 9, 5, 5, 7]
# printing original list
print("The original list is : " + str(test_list))
K = 10
res = find_pairs(test_list, K)
# printing result
print("The paired tuples equal to K  : " + str(res))
 
#This code is contributed by Jyothi Pinjala.


Output

The original list is : [1, 9, 5, 5, 7]
The paired tuples equal to K  : [(1, 9), (5, 5)]

Time complexity: O(n^2), where n is the length of the input test_list. This is because in the worst case, every element in the list will be compared with every other element in the list.
Auxiliary space: O(n), since the result list and seen dictionary will each contain at most n elements.

Method #5: Using nested loop

  1. Initialize a list to store the pairs of elements that sum to K.
  2. Loop through the list and select the first element.
  3. Loop through the remaining elements in the list and compare the sum of the first element and each remaining element with K.
  4. If the sum equals K, add the pair of elements to the list of pairs.
  5. Continue looping through the remaining elements in the list, comparing their sum with the first element, until all pairs have been checked.
  6. Repeat steps 2-5 for all elements in the list.
  7. Return the list of pairs.

Python3




# Python3 code to demonstrate working of
# Construct Sum pairs equal to K
# Using nested loop
 
# initializing list
test_list = [3, 4, 0, 5, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 7
 
# Construct Sum pairs equal to K
# Using nested loop
pairs = []
for i in range(len(test_list)):
    for j in range(i+1, len(test_list)):
        if test_list[i] + test_list[j] == K:
            pairs.append((test_list[i], test_list[j]))
 
# printing result
print("The paired tuples equal to K  : " + str(pairs))


Output

The original list is : [3, 4, 0, 5, 2]
The paired tuples equal to K  : [(3, 4), (5, 2)]

Time complexity: O(n^2), where n is the length of the list, because we are using a nested loop to iterate through the list.
Auxiliary space: O(k), where k is the number of pairs that sum to K, because we are storing each pair in a list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads