a more pythonic way to express conditionally bounded loop?

Posted by msw on Stack Overflow See other posts from Stack Overflow or by msw
Published on 2010-04-26T05:31:07Z Indexed on 2010/04/26 5:33 UTC
Read the original article Hit count: 415

Filed under:
|
|

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).

© Stack Overflow or respective owner

Related posts about python

Related posts about pythonic