For a given list, if for element a, there is no neighbour element greater than a, then is called peak element. Complete the following function which returns the list of peak elements of given list L:
for L = [3,2,4,5,4,3,2,2], the function call tepeNoktalari(L) should return the list [3,5,2].
CodePudding user response:
def findPeak(L):
results = []
for i in range(1, len(L) - 1):
if L[i] > L[i-1] and L[i] > L[i 1]: # check both sides for each
results.append(L[i]) # ^ element of list excluding edge cases
if L[0] > L[1]: results.append(L[0]) # check edge cases
if L[-1] > L[-2]: results.append(L[-1])
return results
array = [3,2,4,5,4,3,2,2]
print("Peak points are: ", findPeak(array))
CodePudding user response:
follow this approach in order to find the peak elements
- check if the 1st element is greater or last index value is greater than 2nd last element
- traverse the array from L[0] to L[n-2]
- check if both neighbours element is greater than L[i], then print the element and terminate the loop
CodePudding user response:
I suggest a numpy solution over a looping/traversal approach, as it will be much more efficent. Consider the following:
L - np.roll(L, shift=1) # difference with left values
L - np.roll(L, shift=1) > 0 # indices of numbers bigger than left neighbor
L - np.roll(L, shift=1) # difference with right values
L - np.roll(L, shift=1) > 0 # indices of numbers bigger than right neighbor
Then clearly we have to take from L numbers bigger than both their left and right values: that means a logical AND between the above indices:
L[(L - np.roll(L, shift=1) > 0) & (L - np.roll(L, shift=-1) > 0)]
This still leaves the last element not correctly checked: this is an easy fix with:
result = L[(L - np.roll(L, shift=1) > 0) & (L - np.roll(L, shift=-1) > 0)]
if L[-1] >= L[-2]:
result = np.append(result, [L[-1]])
CodePudding user response:
Use zip to form tuples of each item in L with the previous and next items (padding with the first and last as needed)
[x for prevX,x,nextX in zip(L[:1] L,L,L[1:] L[-1:]) if prevX <= x >= nextX]
# [3, 5, 2]
