dustinyourface
dustinyourface

Reputation: 313

Iterate through an iterable, how to obtain previous and next value using next()?

def f(iterable):
    i = iter(iterable)
    int_list = []
    n2 = next(i)
    while True:
        n1, n2, n3 = n2, next(i), next(i)
        print('n1', n1)
        print('n2,', n2)
        print('n3', n3)
        if n2 > n1 and n2> n3:
            int_list.append(n2)
    return int_list

In this case, the iterable is a list. I want to check if the integer is bigger than both the previous integer and next integer. However I can't figure out how to assign the proper values to check using the next() method

Upvotes: 2

Views: 188

Answers (5)

user2124834
user2124834

Reputation:

I know you are asking specifically about iterators, but you might also be interested in a solution using list comprehension:

def f(l):
  return [a < b > c for a,b,c in zip(l,l[1:],l[2:])]

For example, for f([1,3,2,5,4]), this returns [True, False, True] (omitting the first and last elements as per the question).

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49320

Start out by turning it into a list, then you're not stuck on a one-way street:

>>> a = [3,5,7,4,6,5,8]
>>> def f(iterable):
...     thelist = list(iterable)
...     return [item for num,item in enumerate(thelist[1:-1]) if max(thelist[num], thelist[num+1], thelist[num+2]) == item]
...
>>> f(a)
[7, 6]

Upvotes: 0

kindall
kindall

Reputation: 184091

collections.deque is ideal for this sort of windowing iterator.

from collections import deque

def f(iterable):
    int_list = []
    it       = iter(iterable)
    n        = deque([next(it), next(it)], maxlen=3)
    for item in it:
        n.append(item)
        if n[0] < n[1] > n[2]:
            int_list.append(items[1])

Upvotes: 1

JuniorCompressor
JuniorCompressor

Reputation: 20015

You could create the following generator:

def f(iterable):
    i = iter(iterable)
    n1, n2, n3 = next(i), next(i), next(i)
    while True:
        if n2 > max(n1, n3):
            yield n2
        n1, n2, n3 = n2, n3, next(i)

and then test like this:

>>> list(f([1, 4, 3, 8, 6]))
[4, 8]

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 992817

It sounds like you could do this with something like:

n1, n2, n3 = next(i), next(i), next(i)
while True:
    # ... do your checks
    n1, n2, n3 = n2, n3, next(i)

You will have to add a suitable termination condition check.

Upvotes: 3

Related Questions