Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Function through List

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?

like image 740
Noob Coder Avatar asked Aug 03 '26 15:08

Noob Coder


2 Answers

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.

like image 155
Claudiu Avatar answered Aug 06 '26 04:08

Claudiu


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.

like image 29
John La Rooy Avatar answered Aug 06 '26 03:08

John La Rooy