Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a more pythonic way to express conditionally bounded loop?

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

like image 617
msw Avatar asked Apr 26 '10 05:04

msw


People also ask

Are for loops Pythonic?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

How do you write a condition in a for loop in Python?

For Loop in Python For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).

Can you have multiple If statements in a while loop Python?

Python compares the two values and if the expression evaluates to true, it executes the loop body. However, it's possible to combine multiple conditional expressions in a while loop as well.

How do you write multiple statements in for loop in Python?

If you want to execute multiple statements for every iteration of the for loop, then indent them accordingly (i.e put them in the same level as the print command).


1 Answers

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
like image 59
bcat Avatar answered Sep 24 '22 23:09

bcat