dir*_*lik 6 python algorithm python-3.x
我有f
接受int
和返回的功能bool
.我想找到的最小非负整数x
,对于这f(x)
是False
.我怎么能用大多数pythonic方式(理想情况下一行)?
我现在就是这样做的:
x = 0
while f(x):
x += 1
print(x)
Run Code Online (Sandbox Code Playgroud)
我想要的东西:
x = <perfect one line expression>
print(x)
Run Code Online (Sandbox Code Playgroud)
在这里,使用next
:
from itertools import count
x = next(i for i in count() if not f(i))
Run Code Online (Sandbox Code Playgroud)
演示:
>>> def f(x):
... return (x - 42)**2
...
>>> next(i for i in count() if not f(i))
42
Run Code Online (Sandbox Code Playgroud)