Find the minimum non-negative integer that does not satisfy the condition

I have a function fthat accepts intand returns bool. I want to find the minimum non-negative integer xfor which f(x)- False. How can I do this in most pythonic (ideally single line)?


Here's how I do it now:

x = 0
while f(x):
    x += 1
print(x)

I need something like:

x = <perfect one line expression>
print(x)
+6
source share
3 answers

Here it is using next:

from itertools import count
x = next(i for i in count() if not f(i))

Demo:

>>> def f(x):
...     return (x - 42)**2
... 
>>> next(i for i in count() if not f(i))
42
+3
source

A similar functional approach with itertools.filterfalseand itertools.countcan be

from itertools import filterfalse, count

x = next(filterfalse(f, count()))

filterfalse dropwhile, , , Python 2 3 ( rici).

from itertools import dropwhile, count
x = next(dropwhile(f, count()))
+3

If you need a single line without importing, one way could be list comprehension (Python 2.7 / PyPy):

def f(x):
  return True if x == 5 else False

x = [g(0) for g in [lambda x: x if f(x) else g(x+1)]][0]

print(x)
+1
source

All Articles