Tuesday, June 9, 2020

Find pair of numbers that will generate target value

Let's say there is a list of values and you are given a target value. How will you find all the pair of numbers when added up will give the target value?

Example:

data = [1,5,11,2,10,9,3,2,10]
target = 12

In this example (1,11), (2,10), (9,3) and (2,10) again will produce the target of 12. However, we don't want to have the sequence of numbers repeating. How can we do that?

There are several ways to do it. However, the clean and easy way to do this is, removing duplicates from the list. How?

data = list(set(data))

We are converting list to set and back to list. This is going to remove duplicate values. Now to get the pairs, we can use list comprehension and produce list of tuples

[(val, target-val) for cnt,val in enumerate(data) if target-val in data[cnt+1:]]

No comments: