Python – Check alternate peak elements in List
Given a list, the task is to write a Python program to test if it’s alternate, i.e next and previous elements are either both smaller or larger across the whole list.
Input : test_list = [2, 4, 1, 6, 4, 8, 0]
Output : True
Explanation : 4, 6, 8 are alternate and peaks (2 1).
Input : test_list = [2, 4, 1, 6, 4, 1, 0]
Output : False
Explanation : 1 is not peak ( 4 < 1 < 0).
Method #1: Using loop.
In this, we check for each element for next and previous elements using conditional if statement to be either smaller or larger, if any variation is found, the result is flagged false and loop is exited.
Python3
test_list = [ 2 , 4 , 1 , 6 , 4 , 8 , 0 ]
print ( "The original list is : " + str (test_list))
res = True
for idx in range ( 1 , len (test_list) - 1 ):
if not ((test_list[idx - 1 ] < test_list[idx]
and test_list[idx + 1 ] < test_list[idx])
or (test_list[idx - 1 ] > test_list[idx]
and test_list[idx + 1 ] > test_list[idx])):
res = False
print ( "Is list forming alternate peaks ? : " + str (res))
|
Output:
The original list is : [2, 4, 1, 6, 4, 8, 0]
Is list forming alternate peaks ? : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using all() + generator expression.
In this, we perform the task of checking for all the elements for getting alternate peaks using all(), and generator expression is used to iterate through the entire list.
Python3
test_list = [ 2 , 4 , 1 , 6 , 4 , 8 , 0 ]
print ( "The original list is : " + str (test_list))
res = all (((test_list[idx - 1 ] < test_list[idx]
and test_list[idx + 1 ] < test_list[idx])
or (test_list[idx - 1 ] > test_list[idx]
and test_list[idx + 1 ] > test_list[idx]))
for idx in range ( 1 , len (test_list) - 1 ))
print ( "Is list forming alternate peaks ? : " + str (res))
|
Output:
The original list is : [2, 4, 1, 6, 4, 8, 0]
Is list forming alternate peaks ? : True
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), no extra space is required
Method #3 : Using NumPy
Python3
import numpy as np
test_list = [ 2 , 4 , 1 , 6 , 4 , 8 , 0 ]
print ( "The original list is : " + str (test_list))
arr = np.array(test_list)
res = np. all (np.diff(np.sign(np.diff(arr))) ! = 0 )
print ( "Is list forming alternate peaks ? : " + str (res))
|
output:
The original list is : [2, 4, 1, 6, 4, 8, 0]
Is list forming alternate peaks ? : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Last Updated :
10 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...