2
Test Array = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2]

I need to iterate through an array in order to find the first time that 3 consecutive entries are <0.5, and to return the index of this occurence.

Test Array = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2]
                           ^       ^    ^    ^
(indices)    [0, 1, 2, 3,  4,  5,  6,   7,   8,  9, 10]
                                   ^

So within this test array the index/value that is being looked for is 6

Alongside a proposed solution, it would be good to know what value gets returned if the '3 consecutive values <0.5' condition is not met - would it simply return nothing? or the last index number?

(I would like the returned value to be 0 if the condition is not met)

jamylak
  • 128,818
  • 30
  • 231
  • 230
Pete Lavelle
  • 103
  • 3
  • 11
  • `http://stackoverflow.com/questions/176918/in-python-how-do-i-find-the-index-of-an-item-given-a-list-containing-it` This link might help you. – pistal Jun 26 '13 at 10:46

2 Answers2

1

You can use zip and enumerate:

def solve(lis, num):
    for i, (x,y,z) in enumerate(zip(lis, lis[1:], lis[2:])):
        if all(k < num for k in (x,y,z)):
            return i
    #default return value if none of the items matched the condition
    return -1    #or use None 
...     

>>> lis = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2]
>>> solve(lis, 0.5)
6
>>> solve(lis, 4)   # for values >3 the answer is index 0, 
0                   # so 0 shouldn't be the default  return value.
>>> solve(lis, .1)
-1

Use itertools.izip for memory efficient solution.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0
from itertools import groupby
items = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2]

def F(items, num, k):
    # find first consecutive group < num of length k
    groups = (list(g) for k, g in groupby(items, key=num.__gt__) if k)
    return next((g[0] for g in groups if len(g) >= k), 0)

>>> F(items, 0.5, 3)
0.1
jamylak
  • 128,818
  • 30
  • 231
  • 230