# Program to find any two numbers in a list that sums up to k 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 have a list of numbers called nums and we have another number k, we have to check whether any two numbers present in the list add up to k or now. Same elements must not be used twice. And numbers can be negative or 0.

So, if the input is like nums = [45, 18, 9, 13, 12], k = 31, then the output will be True, as 18 + 13 = 31

To solve this, we will follow these steps −

• temp_set:= a new set
• for each num in nums, do
• if num is in temp_set, then
• return True
• add (k-num) into temp_set
• return False

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, nums, k):
temp_set=set()
for num in nums:
if num in temp_set:
return True
nums = [45, 18, 9, 13, 12] k = 31 print(ob.solve(nums, k))
[45, 18, 9, 13, 12], 31
True