2

I have an array and function and I would like the function to return a list of indices in which the difference of two consecutive elements passes a threshold.

I have:

def func (y, t=100):
    for i in range(1, len(y)): #Range skips 1st element
        if abs(y[i] - y[i-1]) > t:
            return(i)

The problem I'm facing is that this function only returns the first index where my if statement is true. How do I get the rest of them?

2
  • yield i and collect items in a list(In other words convert your function to a generator function) Commented Jun 5, 2018 at 4:03
  • Don't return it. Just capture it. Commented Jun 5, 2018 at 4:05

3 Answers 3

4

There are two ways. First, yield instead of return will give you a generator:

def func (y, t=100):
    for i in range(1, len(y)): #Range skips 1st element
        if abs(y[i] - y[i-1]) > t:
            yield(i)

Or add a list in you function:

def func (y, t=100):
    output = []
    for i in range(1, len(y)): #Range skips 1st element
        if abs(y[i] - y[i-1]) > t:
            output.append(i)
    return output
Sign up to request clarification or add additional context in comments.

Comments

4

With a list comprehension you can do that like:

Code:

def peak_detect(in_data, threshold=100):
    return [i for i, (x, y) in enumerate(zip(in_data, in_data[1:]))
            if abs(y - x) >= threshold]

Test Code:

data = [1, 2000, 2001, 4000]

print(peak_detect(data))

Result:

[0, 2]

Comments

2
def peak_detect (y_, threshold=100):
    indicesList = []
    for i in range(1, len(y_)): #Range skips 1st element
        if abs(y[i] - y[i-1]) > threshold:
            indicesList.append(i)
    return(indicesList)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.