Python Chapter Seven After-Class Exercises (11)

Complete the function fun11() to find the indexes of all peaks from the one-dimensional array data. Note: The peak point is greater than the data value on the left and right sides, excluding the end point.
Hint: For the question of np.diff,np.sign,np.where(condition)
,
first obtain their difference, and use the sign function conversion to facilitate the calculation. The
sample result is
[2 4 -6 1 4 -6 1]
[1 1 -1 1 1 -1 1]
To find the peak value, which is larger than the front and back.
So when using diff, the number is -1 which means it is bigger than the latter, and the number is 1 which means it is smaller than the latter. Do
another diff, the result is
[0 -2 2 0 -2 2]
The point where the result is -2 must be -1-1
meaning that I am larger than the latter, but the data corresponding to the previous index is smaller than the latter, which is the peak value.
So why is it not 2?
If data=[9, 3, 7, 1,2, 6, 0, 1], the
result is that [0,2,5]
has one more end point, then it is very easy to understand,
so find the point of -2 and then +1 The index is
+1 because len will be -1 after diff,

def fun11(data=[1, 3, 7, 1, 2, 6, 0, 1]):
    """
    Arg:
        data : a list as input; e.g. [1, 3, 7, 1, 2, 6, 0, 1]
    return a numpy ndarray; e.g. [2 5]
    
    """
    nump=np.array(data)
    cha=np.diff(nump)
    sign=np.sign(cha)
    cha1=np.diff(sign)
    res0=np.where(cha1==-2)[0]+1
    return res0

Guess you like

Origin blog.csdn.net/qq_53029299/article/details/115121117