Skip to content
Related Articles

Related Articles

Python – Test for strictly decreasing list

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

The test for a monotonic sequence is a utility that has manifold applications in mathematics and hence every sphere related to mathematics. As mathematics and Computer Science generally go parallel, mathematical operations such as checking for strictly decreasing sequences can be useful to gather knowledge. Let us discuss certain ways to perform this test. 

Method #1 : Using all() + zip() The all() generally checks for all the elements fed to it. The task of zip() is to link list beginning from the beginning and list beginning from the first element, so that a check can be performed on all elements. 

Python3




# Python 3 code to demonstrate
# Test for strictly decreasing list
# using zip() + all()
 
# initializing list
test_list = [10, 8, 7, 5, 4, 1]
 
# printing original lists
print ("Original list : " + str(test_list))
 
# using zip() + all()
# Test for strictly decreasing list
res = all(i > j for i, j in zip(test_list, test_list[1:]))
 
# printing result
print ("Is list strictly decreasing ? : " + str(res))

Output : 

Original list : [10, 8, 7, 5, 4, 1]
Is list strictly decreasing ? : True

Method #2 : Using reduce() + lambda reduce() coupled with lambda can also perform this task of checking for monotonicity. reduce function is used to cumulate the result as True or False, lambda function checks for each index value with next index value. 

Python3




# Python 3 code to demonstrate
# Test for strictly decreasing list
# using reduce() + lambda
 
# initializing list
test_list = [10, 8, 7, 5, 4, 1]
 
# printing original lists
print ("Original list : " + str(test_list))
 
# using reduce() + lambda
# Test for strictly decreasing list
res = bool(lambda test_list: reduce(lambda i, j: j if i > j else 9999, test_list) != 9999)
 
# printing result
print ("Is list strictly decreasing ? : " + str(res))

Output : 

Original list : [10, 8, 7, 5, 4, 1]
Is list strictly decreasing ? : True

Method #3 : Using sort() and extend() methods

Python3




# Python3 code to demonstrate
# to check for strictly decreasing list
 
# initializing list
test_list = [10, 8, 7, 5, 4, 1]
 
# printing original lists
print ("Original list : " + str(test_list))
 
# to check for strictly decreasing list
res=False
x=[]
x.extend(test_list)
test_list.sort(reverse=True)
if(x==test_list):
    res=True
# printing result
print ("Is list strictly decreasing ? : " + str(res))

Output

Original list : [10, 8, 7, 5, 4, 1]
Is list strictly decreasing ? : True

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!