K Sum Pairs
Write a program to find all the unique pairs whose sum is equal to K.
Input
The first line of input will contain comma-separated integers.
The second line of input will contain an integer (K).
Output
The output should be M lines equal to the number of unique pairs sorted in ascending order.
Each line should contain a unique pair as a tuple with the smallest number first.
Explanation
For example, if the given string is “5,3,7,9,5” and K is 12. Your code should print the unique pairs of numbers, whose sum is equal to K. In the above numbers
3+9 12
5+7 12
as these are tne unique pairs with sum equal to 12, print eacn pair as a tuple. So the output should be
(3, 9)
(5, 7)
Sample Input 1
5,3,7,9, 5
12
Sample Output 1
(3, 9)
(5, 7)
Code:
def get_unique_pairs(int_list, pair_sum):
stop_index = len(int_list) - 1
unique_pairs_set = set()
for cur_index in range(stop_index):
num_1 = int_list[cur_index]
num_2 = pair_sum - num_1
remaining_list = int_list[cur_index+1:]
if num_2 in remaining_list:
pair = (num_1, num_2)
#avoid duplicates like (5,7) & (7,5)
sorted_pair = tuple(sorted(pair))
unique_pairs_set.add(sorted_pair)
return unique_pairs_set
def convert_string_to_int(str_num_list):
new_list = []
for item in str_num_list:
num = int(item)
new_list.append(num)
return new_list
str_num_list =input().split(",")
pair_sum = int(input())
int_list = convert_string_to_int(str_num_list)
unique_pairs = get_unique_pairs(int_list, pair_sum)
unique_pairs = list(unique_pairs)
unique_pairs.sort() #sort the tuples according to the first element
for pair in unique_pairs:
print(pair)
Input
-4,-3,-2, -1,0,1,2,3,4,5,6
1
Output
(-4, 3)
(-3, 2)
(-2, 1)
(-1, 0)