Python – Extract element with relative difference greater than K

• Last Updated : 09 May, 2021

Given a list of numbers, the task is to write a Python program to extract all numbers with differences of the next and previous element with a current is 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 : 

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 is 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]

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]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :