Python – Non K distant elements
Last Updated :
28 Feb, 2023
Given a list, the task is to write a Python program to extract all the elements such that no element is at K distant from one other.
Examples:
Input : test_list = [8, 10, 16, 20, 3, 1, 7], K = 2
Output : [16, 20, 7]
Explanation : 16 + 2 = 18, 16 – 2 = 14, both are not in list, hence filtered.
Input : test_list = [8, 10, 16, 20], K = 2
Output : [16, 20, 7]
Explanation : 16 + 2 = 18, 16 – 2 = 14, both are not in list, hence filtered.
Method #1: Using loop
In this we iterate for all the elements and using in operator check for each element if has element at K distance from it, if found, its not included in list.
Python3
test_list = [ 8 , 10 , 16 , 20 , 3 , 1 , 7 ]
print ( "The original list is : " + str (test_list))
K = 2
res = []
for ele in test_list:
if ele + K not in test_list and ele - K not in test_list:
res.append(ele)
print ( "The filtered List : " + str (res))
|
Output
The original list is : [8, 10, 16, 20, 3, 1, 7]
The filtered List : [16, 20, 7]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using list comprehension
In this, we perform task of filtering and iteration using 1 liner using list comprehension.
Python3
test_list = [ 8 , 10 , 16 , 20 , 3 , 1 , 7 ]
print ( "The original list is : " + str (test_list))
K = 2
res = [ele for ele in test_list if ele +
K not in test_list and ele - K not in test_list]
print ( "The filtered List : " + str (res))
|
Output
The original list is : [8, 10, 16, 20, 3, 1, 7]
The filtered List : [16, 20, 7]
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...