Python program to find Non-K distant elements

PythonServer Side ProgrammingProgramming

When it is required to find non ‘K’ distant elements, a simple iteration along with the ‘append’ method is used.

Example

Below is a demonstration of the same

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]

Explanation

  • A list is defined and is displayed on the console.

  • The key value is defined and displayed on the console.

  • An empty list is defined.

  • The list is iterated over, and the key is checked to see if it is present in the list or not.

  • If yes, it is appended to the empty list.

  • The output is displayed on the console.

raja
Published on 20-Sep-2021 08:38:54
Advertisements