Skip to content
Related Articles

Related Articles

Python program to test if all elements in list are maximum of K apart

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

Given a list of numbers, the task is to write a Python program to test if all elements are maximum of K apart.

Examples:

Input : test_list = [475, 503, 425, 520, 470, 500], K = 100
Output : True 
Explanation : Maximum element is 520 and minimum is 425, 520-425 = 95, which is less than 100, hence elements are in range.

Input : test_list = [475, 503, 425, 540, 470, 500], K = 100
Output : False 
Explanation : Maximum element is 540 and minimum is 425, 520-425 = 115, which is more than 100, hence elements are not in range.

Method #1 : Using sort()

In this, we perform the task of sorting elements to get the min and max elements accessible using sort(). The next step is to get the difference among them, if less than the range, True is returned.

Python3




# Python3 code to demonstrate working of
# Test if all elements are in range size
# Using sort()
 
# initializing list
test_list = [475, 503, 425, 520, 470, 500]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 100
 
# sorting list
test_list.sort()
 
# checking if greater than range
res = test_list[-1] - test_list[0] < K
 
# printing result
print("Are elements in range ? : " + str(res))

Output

The original list is : [475, 503, 425, 520, 470, 500]
Are elements in range ? : True

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

Method #2 : Using min() + max()

Instead of changing the ordering or original list, min() and max() are used to get minimum and maximum elements respectively, and the difference between them gets the required result.

Python3




# Python3 code to demonstrate working of
# Test if all elements are in range size
# Using min() + max()
 
# initializing list
test_list = [475, 503, 425, 520, 470, 500]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 100
 
# using min() and max() rather than
# changing order
res = max(test_list) - min(test_list) < K
 
# printing result
print("Are elements in range ? : " + str(res))

Output

The original list is : [475, 503, 425, 520, 470, 500]
Are elements in range ? : True

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!