Skip to main content
2 of 6
Add explanation
TheBlackCat
  • 2.4k
  • 11
  • 10

Here is an alternative approach using set logic:

n = 181
numbers = [80, 98, 83, 92, 1, 38, 37, 54, 58, 89]
numset = set(numbers)
goodnums = {n-x for x in numbers if x<=n//2} & numset
pairs = [(n-x, x) for x in goodnums]

What this does is first filter out values that are greater than 1/2 the target value, since one number in each pair must be that way. Then it subtracts the remaining numbers from the target (in this case 181). This gets the other value from the pair. Then it uses set logic to extract only those values where the other value is present in the original list of numbers.

So to put it more briefly, it finds all values x such that 181-x is also present in the list.

TheBlackCat
  • 2.4k
  • 11
  • 10