# Program to create data structure to check pair sum is same as value in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we want to make a data structure that has two methods −

• find(val) this checks whether there are two elements whose sum is val or not

We have to design this so that we can get the result on the fly. We will not search for numbers every time when a query comes.

So, if the input is like create an object obj and add few numbers 6, 14, 3, 8, 11, 15, then check like obj.find(9), obj.find(11), obj.find(15), then the output will be True, True, False as 9 can be formed with 6+3, 11 can be formed with 3+8. Now 15 is present in the data structure but no two numbers' sum is same as 15.

To solve this, we will follow these steps −

• Define the constructor.
• nums := a new set
• multiple := a new set
• Define a function add(). This will take val
• insert val into multiple
• otherwise,
• insert val into nums
• Define a function find() . This will take val
• for each n in nums, do
• if n + n is same as val, then
• return true when n is in multiple
• otherwise when val - n is in nums, then
• return True
• return False

## Example

Let us see the following implementation to get better understanding −

class PairSumChecker:
def __init__(self):
self.nums = set()
self.multiple = set()

if val in self.nums:
else:

def find(self, val):
for n in self.nums:
if n + n == val:
return n in self.multiple
elif val - n in self.nums:
return True
return False

obj = PairSumChecker()

print(obj.find(9))
print(obj.find(11))
print(obj.find(15))

## Input

print(obj.find(9))
print(obj.find(11))
print(obj.find(15))

## Output

True
True
False
Updated on 14-Oct-2021 10:24:49