3

I have a function prime(x) that returns True if x is prime and False if x is false.

Is there an efficient way to iterate through a list and if all the members satisfy the function, return True, and otherwise return false?

For the prime example, I wrote:

def primecheck(x):
    for index in xrange(0,len(x)):
        if prime(x[index])==False:
            return False
            break
    return True

but I imagine that this is inefficient and there must be a much better way of doing it.

Is there a standard method for iterating a generic function (where I define a generic function as something that evaluates an integer or string to be True or False) through a list without having to do something like the above each time? Or even if there isn't a standard method, is there a more efficient method than running through the index of the list?

2 Answers 2

3

Yep! Use all in tandem with a generator expression:

def primecheck_all(x):
    return all(prime(n) for n in x)

That's about the same as doing the following:

def primecheck_longway(x):
    for n in x:
        if not prime(n):
            return False
    return True

Doing some timing, it seems that primecheck_longway is actually faster, though, although primecheck_all is much easier to read. primecheck_xrange (your version) is slowest:

>>> def prime(n): 
        #simple function so all timing goes to how the list check is done
        return n % 2 == 0

>>> l = range(100)
>>> timeit.timeit(lambda: primecheck_all(l))
1.4247075990295475
>>> timeit.timeit(lambda: primecheck_longway(l))
0.6282418298159413
>>> timeit.timeit(lambda: primecheck_xrange(l))
1.161489160644436

>>> l = range(2,100,2)
>>> timeit.timeit(lambda: primecheck_all(l))
10.058764784981875
>>> timeit.timeit(lambda: primecheck_longway(l))
7.728265179204939
>>> timeit.timeit(lambda: primecheck_xrange(l))
10.481824344034152

This is likely due to not having to have the overhead of the generator. That's a 2.3 second difference for one million iterations, to put it in perspective.

Sign up to request clarification or add additional context in comments.

2 Comments

Pretty cool! Just one suggestion: try not to use l for identifier, easily messed up with one 1.
Wow. I did not expect all to be that much slower.
1

Your code is really similar to how all works anyway. A few changes to your code gives this

def primecheck(x):
    for i in x:
        if not prime(i):
            return False
    return True

All I changed was to loop over x instead of the range, and to remove the unnecessary break.

Using all is neater, but the long hand version works for very very old versions of Python (<2.5) too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.