1

Can you reset iterators? Or is there a way to save the next element without iterating through it?

Rimoun
  • 455
  • 1
  • 9
  • 16
  • Your example is not clear, you are saying "terator who are greater than the element before and after it." what is the element that u r calculating based on it, the elemnt before/after it. – user3378649 Nov 04 '14 at 23:58

3 Answers3

3

You can use itertools.tee to "remember" previous values of an iterator

>>> from itertools import tee, izip
>>> it = iter([0,1,-1,3,8,4,3,5,4,3,8])
>>> it1, it2, it3 = tee(it, 3)
>>> next(it2)
0
>>> next(it3)
0
>>> next(it3)
1
>>> [j for i, j, k in izip(it1, it2, it3) if i < j > k]
[1, 8, 5]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

It comes up to my mind to keep a small buffer of the last two elements in two separate variables, a tuple, a list, etc and compare with the current element in the iterator.

Salvador Medina
  • 5,833
  • 1
  • 19
  • 19
0

By excluding cases where the element is in the edge (head, tail), we traverse the element by comparing every element to predecessor/successor, if it's verifying the criteria, we add it to the list.

x= [0,1,-1,3,8,4,3,5,4,3,8]

s= [ x[i] for i in xrange(1,len(x)-2) if x[i-1]< x[i] and x[i]> x[i+1] ]

print s  #Output: [1, 8, 5]

UPDATE

In this case, we would use while to loop into iter, and every time we store datat into three variable left, middle, right. Whenever we call the next variable, we shift middle to left, last to middle and store the next new value in last.

l= iter([0,1,-1,3,8,4,3,5,4,3,8])

res= []

left,middle,last= l.next(),l.next(),l.next() #Initialize data, we assume that we have at least 3 items, otherwise, we will get exception

while  True:
    try:
        if left<middle and middle>last: # I made first, to check in case we got that case in the first three items
            res+=[middle]
        left=middle
        middle= last
        last= l.next()
    except StopIteration:
        break

print res #Output: [1, 8, 5]
  • The problem is I can't make x a list. X is an iterator. next(x)=0, next(x)=1, next(x)=-1, next(x)=3.... Also for the head and tail, they would just consider one side of them, the end side would be always true. – Rimoun Nov 05 '14 at 00:13