user6952870 user6952870 - 1 month ago 8
Python Question

Function, that returns peak values

def peaks(iterable):
z = []
i = iter(iterable)
v2 = next(i)

try:
while True:
v1, v2 = v2, next(i)
if v1 > v2:
z.append(v1)
elif v1 < v2:
continue
except StopIteration:
pass

return z


This function returns a list of int for those values in the iterable that are bigger than the value preceding and following them:
peaks([0, 1, -1, 3, 8, 4, 3, 5, 4, 3, 8])
returns
[1, 8, 5]
. This result means the values 1, 8, and 5 are strictly bigger than the value preceding and following them.

But when I took
[0, 1, -1, 3, 8, 4, 3, 5, 4, 3, 8]
it returns
[1, 8, 4, 5, 4]
instead of
[1, 8, 5]
.

And when I took
[5, 2, 4, 9, 6, 1, 3, 8, 0, 7]
it returns
[5, 9, 6, 8]
instead of
[9, 8]
.

Can someone tell me how to fix it? Thanks.

DJV DJV
Answer

You are returning values, which are bigger than the following. You also need to check if they are bigger than previous.

def peaks(iterable):
    z = []
    i = iter(iterable)

    try:
        v2 = next(i)
        v3 = next(i)
        while True:
            v1, v2, v3 = v2, v3, next(i)
            if v2 > v1 and v2 > v3:
                z.append(v2)
    except StopIteration:
        pass

    return z

print(peaks([0, 1, -1, 3, 8, 4, 3, 5, 4, 3, 8]))  # [1, 8, 5]

Won't find peak in [0, 1, 1, 0]. Hopefully, that is what you want.