I’m trying to write Python code to find all unique pairs from a list of numbers where the sum of each pair equals a specific target. So far, my basic idea looks like this:
def find_unique_pairs(numbers, target):
seen = set()
pairs = set()
for num in numbers:
complement = target - num
if complement in seen:
# I want to add the pair here in a way that avoids duplicates
pass # What should I do here?
seen.add(num)
return list(pairs)
# Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
target = 10
print(find_unique_pairs(numbers, target))
I’m struggling with how to add the pairs to the pairs set in a way that ensures no duplicates (e.g., (2, 8) and (8, 2) should count as the same pair) Could you help me complete the code and possibly suggest improvements to make it more efficient for larger lists?
I tried using sets to store seen numbers and pairs, but I’m struggling with how to format the pairs correctly to avoid duplicates. I expect the result to include unique pairs like (2, 8), (3, 7), and (4, 6) when the target is 10your text
I assume that by "duplicate" you mean, for example (3, 7) and (7, 3).
If that is the case then:
from itertools import combinations
# added another 3 so that there's at least one significant duplicate
data = [1, 2, 3, 3, 4, 5, 6, 7, 8]
target = 10
results = set()
print(data)
for a, b in combinations(data, r=2):
if a + b == target:
if a > b:
results.add((b, a))
else:
results.add((a, b))
print(results)
Output:
[1, 2, 3, 3, 4, 5, 6, 7, 8]
{(3, 7), (4, 6), (2, 8)}