
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find any two numbers in a list that sums up to k in Python
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
- if num is in temp_set, then
- return False
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, k): temp_set=set() for num in nums: if num in temp_set: return True temp_set.add(k-num) return False ob = Solution() nums = [45, 18, 9, 13, 12] k = 31 print(ob.solve(nums, k))
Input
[45, 18, 9, 13, 12], 31
Output
True
- Related Articles
- Program to check sum of two numbers is up to k from sorted List or not in Python
- Program to find number of distinct combinations that sum up to k in python
- Program to count subsets that sum up to k in python
- Program to find k sublists with largest sums and return sums in ascending order in Python
- Program to find missing numbers from two list of numbers in Python
- Program to find largest distance pair from two list of numbers in Python
- Program to find a list of numbers where each K-sized window has unique elements in Python
- Program to find minimum possible sum by changing 0s to 1s k times from a list of numbers in Python?
- Python program to find the group sum till each K in a list
- Python Program to remove elements that are less than K difference away in a list
- Program to find minimum number of Fibonacci numbers to add up to n in Python?
- Program to find the K-th last node of a linked list in Python
- Program to find number of sublists with sum k in a binary list in Python
- Program to find linked list intersection from two linked list in Python
- Python program to print even numbers in a list

Advertisements