1

I've got a list organized like this :

[('down', 0.0098000000000000309), 
('up', 0.0015000000000000568), 
('down', 0.008900000000000019), 
('down', 0.023300000000000098), 
('down', 0.011599999999999944), 
('down', 0.0027000000000000357), 
('up', 0.0023999999999999577), 
('up', 0.0065000000000000613), 
('down', 0.0057000000000000384), 
('down', 0.018400000000000083), 
('up', 0.009300000000000086), 
('down', 0.0038000000000000256), 
('down', 0.00050000000000005596), 
('up', 0.0082000000000000961), .....

What would be the best way to "compare backwards?" , basically I want to return "yes" ( or whatever .. ) IF we`ve got a series of 2 "downs" followed by one "up" AND the second value is inferior to 0.0095 .

I hope he makes sense ..

sra
  • 23,820
  • 7
  • 55
  • 89
Finger twist
  • 3,546
  • 9
  • 42
  • 52
  • 2
    [This question](http://stackoverflow.com/questions/323750/) shows how to iterate over a list using a sliding window. The rest should be simple enough. – Björn Pollex May 26 '11 at 09:58

5 Answers5

5

Create a sliding window, and test on that:

def slidingwindow(iterable):
    iterator = iter(iterable)
    first, second = iterator.next(), iterator.next()
    for next in iterator:
        yield (first, second, next)
        first, second = second, next

def testforcondition(data):
    for window in slidingwindow(data):
        direction = [w[0] for w in window]
        if direction == ['down', 'down', 'up'] and window[2][1] < 0.0095:
            return True
    return False
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

Here you go:

def frob(l):
    downcount = 0
    for ele in l:
        if downcount >= 2 and ele[0] == 'up' and ele[1] < 0.0095:
                return True
        downcount = (downcount + 1) if ele[0] == 'down' else 0
    return False
verdesmarald
  • 11,646
  • 2
  • 44
  • 60
0

Here's my attempt:

def test(data):
  for x in xrange(2, len(data)):
    if data[x-2][0] is 'down' and data[x][x-1] is 'down' and data[x][0] is 'up' and data[x][1] < 0.0095:
      return True
  return False
sje397
  • 41,293
  • 8
  • 87
  • 103
0

My suggestion (although now with the third slice, this is not really pretty anymore):

def compback(l):
    return any(i1[0] == i2[0] == "down" 
               and i2[1] < 0.0095
               and i3[0] == "up"
               for i1, i2, i3 in zip(l, l[1:], l[2:]))
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0
for index in xrange(0, len(list) - 2):
    if list[index][0] == 'down' and list[index + 1][0] == 'down' and list[index + 2][0] == 'up' and list[index + 1][1] < 0.0095:
         return True
Sebastian Blask
  • 2,870
  • 1
  • 16
  • 29