Skip to content
Related Articles

Related Articles

Python – Extract element with relative difference greater than K

View Discussion
Improve Article
Save Article
  • Last Updated : 24 Aug, 2022
View Discussion
Improve Article
Save Article

Given a list of numbers, the task is to write a Python program to extract all numbers with differences of the next and previous elements with a current greater than K.

Input : test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5], K = 4
Output : [9, 10]
Explanation : 9 has 1 as preceding element and 2 as succeeding. 8 and 7 are its difference respectively which are greater than 4.

Input : test_list = [2, 7, 4, 1, 9, 2], K = 4
Output : [9]
Explanation : 9 has 1 as preceding element and 2 as succeeding. 8 and 7 are its difference respectively which are greater than 4.

Method #1: Using loop

In this, we check using brute force if the next or previous element has elements less than K difference and omit them. Loop is used for the iteration of all the elements.

Python3




# Python3 code to demonstrate working of
# Extract element with relative difference
# greater than K Using loop
 
# initializing list
test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
res = []
for idx in range(1, len(test_list)):
 
    # using abs to get absolute difference
    if abs(test_list[idx - 1] - test_list[idx]) > K\
            and abs(test_list[idx + 1] - test_list[idx]) > K:
        res.append(test_list[idx])
 
# printing result
print("The extracted difference elements : " + str(res))

Output

The original list is : [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
The extracted difference elements : [9, 10]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using list comprehension

This is similar to the above method, the difference only being the usage of list comprehension for availing a shorthand to solving the issue. 

Python3




# Python3 code to demonstrate working of
# Extract element with relative difference
# greater than K Using list comprehension
 
# initializing list
test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# using abs to get absolute difference
# list comprehension provides shorthand
res = [test_list[idx] for idx in range(
  1, len(test_list)) if abs(test_list[idx - 1] - test_list[idx]) > K
       and abs(test_list[idx + 1] - test_list[idx]) > K]
 
# printing result
print("The extracted difference elements : " + str(res))

Output

The original list is : [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
The extracted difference elements : [9, 10]

Time Complexity: O(n)
Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!