a more pythonic way to express conditionally bounded loop?
coding-style, python
Solution
Maybe something like this would be a little better:
from itertools import ifilter, islice
def ello_bruce(limit=None):
for i in islice(ifilter(predicate, xrange(10**5)), limit):
# do whatever you want with i here
Problem
I've got a loop that wants to execute to exhaustion or until some user specified limit is reached. I've got a construct that looks bad yet I can't seem to find a more elegant way to express it; is there one? ``` def ello_bruce(limit=None): for i in xrange(10**5): if predicate(i): if not limit is None: limit -= 1 if limit <= 0: break def predicate(i): # lengthy computation return True ``` Holy nesting! There has to be a better way. For purposes of a working example, `xrange` is used where I normally have an iterator of finite but unknown length (and predicate sometimes returns False).