Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find Non-K distant elements
When it is required to find non 'K' distant elements, a simple iteration along with the 'append' method is used. Non-K distant elements are those numbers in a list that do not have any other number at exactly K distance from them.
What are Non-K Distant Elements?
An element is considered non-K distant if neither (element + K) nor (element - K) exists in the same list. For example, with K=2, the number 91 is non-K distant if neither 89 nor 93 exists in the list.
Example
Below is a demonstration of finding non-K distant elements ?
my_list = [91, 13, 19, 25, 35, 3, 9, 11, 0]
print("The list is :")
print(my_list)
my_key = 2
print("The key is")
print(my_key)
my_result = []
for element in my_list:
if element + my_key not in my_list and element - my_key not in my_list:
my_result.append(element)
print("The resultant list is :")
print(my_result)
Output
The list is : [91, 13, 19, 25, 35, 3, 9, 11, 0] The key is 2 The resultant list is : [91, 19, 25, 35, 3, 0]
How It Works
Let's trace through the logic with K=2 :
91: Neither 89 nor 93 exists in the list ? Non-K distant
13: 11 exists in the list (13-2=11) ? K distant
19: Neither 17 nor 21 exists in the list ? Non-K distant
9: 11 exists in the list (9+2=11) ? K distant
Alternative Implementation Using List Comprehension
The same logic can be implemented more concisely using list comprehension :
my_list = [91, 13, 19, 25, 35, 3, 9, 11, 0]
my_key = 2
my_result = [element for element in my_list
if element + my_key not in my_list and element - my_key not in my_list]
print("Non-K distant elements:", my_result)
Non-K distant elements: [91, 19, 25, 35, 3, 0]
Conclusion
Non-K distant elements are identified by checking if neither (element + K) nor (element - K) exists in the list. This algorithm has O(n²) time complexity due to the 'in' operator being called for each element.
