
- 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 check we can find four elements whose sum is same as k or not in Python
Suppose we have a list of numbers called nums and a value k, we have to check whether there are four unique elements in the list that add up to k.
So, if the input is like nums = [11, 4, 6, 10, 5, 1] k = 25, then the output will be True, as we have [4, 6, 10, 5] whose sum is 25.
To solve this, we will follow these steps −
sort the list nums
n := size of nums
for i in range 0 to n − 4, do
for j in range i + 1 to n − 3, do
l := j + 1, h := size of nums − 1
while l < h, do
summ := nums[i] + nums[j] + nums[l] + nums[h]
if summ is same as k, then
return True
otherwise when summ < k, then
l := l + 1
otherwise,
h := h − 1
return False
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, k): nums.sort() n = len(nums) for i in range(n - 3): for j in range(i + 1, n - 2): l, h = j + 1, len(nums) - 1 while l < h: summ = nums[i] + nums[j] + nums[l] + nums[h] if summ == k: return True elif summ < k: l += 1 else: h −= 1 return False ob1 = Solution() nums = [11, 4, 6, 10, 5, 1] k = 25 print(ob1.solve(nums, k))
Input
[11, 4, 6, 10, 5, 1], 25
Output
True
- Related Articles
- Program to check we can find three unique elements ose sum is same as k or not Python
- Program to check n can be shown as sum of k or not in Python
- Program to check n can be represented as sum of k primes or not in Python
- Program to check whether we can convert string in K moves or not using Python
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to find three unique elements from list whose sum is closest to k Python
- C++ program to find range whose sum is same as n
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to check we can reach leftmost or rightmost position or not in Python
- Python program to check whether we can pile up cubes or not
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Program to check we can cross river by stones or not in Python
- Program to check we can form array from pieces or not in Python
- Program to check whether we can make group of two partitions with equal sum or not in Python?

Advertisements