Print all the peaks and troughs in a list of Integers in Python

Our task is to find all the peaks and troughs in the given list of integers by the user in Python.

We are given the list of integers.

Now the first question which comes to our mind is what is this peak and trough in the list?

PEAK:

It is the element in the list which is greater than its neighbors.

TROUGH:

It is an element in the list which is smaller than its neighbors.


Now again here is the approach to find the peaks in the list.

To find peaks we need to check that the first element in the list is greater than its next element or not.

If yes then it is one of the peaks. If not the check the same for the last element.

Now for the elements in the middle, we need every element whether it is greater than the last and preceding one if it is then it is the peak.

Now again here is the approach to find the troughs in the list.

To find trough we need to check that the first element in the list is lesser than its next element or not.

If yes then it is one of the troughs. If not the check the same for the last element.

Now for the elements in the middle, we need every element whether it is less than the last and preceding one if it is then it is the trough.

Find all the peaks and troughs in the given list of integers in Python

Here is the code to do this operation.

print("Enter the items in the list")
l=list(map(int,input().split()))
print("The given list is : ",end=" ")
print(l)
p,n,c=0,0,0
d=[]
f=[]
if l[0] > l[1]:
    d.append(l[0])
if l[0]<l[1]:
    f.append(l[0])
if l[-1]>l[-2]:
    d.append(l[-1])
if l[-1]<l[-2]:
    f.append(l[-1])
for i in range(1,len(l)):
    p=i-1
    n=i+1
    c=i
    if p>=0 and n<len(l) and c<len(l):
        if l[p]<l[c] and l[n]<l[c]:
            d.append(l[c])
        if l[p]>l[c] and l[n]>l[c]:
            f.append(l[c])
print("The peaks present in the given list is : ",d)
print("The trough present in the given list is : ",f)

Here the output of the following program:

Print peaks and troughs in a list of Integers in Python output

 

Also, read: How to Get the Number of Elements in a Python List

Leave a Reply

Your email address will not be published. Required fields are marked *