I would like to test whether a certain value belongs to a sequence of numbers, which is produced using an iterator. Of course when the value does belong to the sequence, one can stop as soon as the value is met. But when it does not, I guess that's when problems show up.
However one can use additional information (e.g., the sequence is increasing).
Consider the Fibonacci example:
class FibonacciIterator(object):
def __init__(self):
self.mem = [0, 1]
def __next__(self):
curr = self.mem[0]
new = self.mem[0]+self.mem[1]
self.mem[0] = self.mem[1]
self.mem[1] = new
return curr
class Fibonacci(object):
def __iter__(self):
return FibonacciIterator()
If one tests whether 8
belongs to the sequence then everything is fine:
>>> fib = Fibonacci()
>>> 8 in fib
True
If, however, one tests 10
(which doesn't belong to the sequence) then
>>> 10 in fib
...
never terminates. But one could easily determine that 10
is not in the sequence by observing that after 8
comes 13
, and since the sequence is increasing then necessarily not 10 in fib
.
Is there a nice way in Python to implement such behavior of in
, so that 10 in fib
terminates?