Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum non-negative integer, which not satisfies the condition

I have function f that takes int and return bool. I want to find minimum non-negative integer x, for which f(x) is False. How can I do it in most pythonic way (ideally one line)?


Here is how I do it now:

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

I want something like:

x = <perfect one line expression>
print(x)
like image 659
diralik Avatar asked Sep 12 '17 18:09

diralik


1 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
like image 184
wim Avatar answered Oct 06 '22 00:10

wim