我将使用我的例子:我想用Eratosthenes的筛子创建一个素数列表。 对于每个数字,我检查它是否是复合数,如果没有,我将它附加到列表中。
使用“标准”编程:
primes = [2] start = time.time() for i in xrange(3,primeRange,2): isPrime = True for p in primes: if(i % p == 0): isPrime = False break; if(isPrime): primes.append(i) print "Using C++-style: ", time.time() - start, " seconds"使用reduce功能:
start = time.time() for i in xrange(3,primeRange,2): if(reduce(lambda x,y:x and y,[i % p != 0 for p in primes])): primes.append(i) print "Using map-reduce: ", time.time() - start, " seconds"primeRange = 100000的结果:
Using map-reduce: 54.1150000095 seconds Using C++-style: 4.62000012398 seconds第二种情况使代码更紧凑,但是将对整个列表评估条件,然后将其简化为True / False 。 有没有办法避免这种情况?
I will use my example: I want to create a list of primes using the sieve of Eratosthenes. For each number, I check if it is composite, and if not, I append it to the list.
Using "standard" programming:
primes = [2] start = time.time() for i in xrange(3,primeRange,2): isPrime = True for p in primes: if(i % p == 0): isPrime = False break; if(isPrime): primes.append(i) print "Using C++-style: ", time.time() - start, " seconds"Using reduce function:
start = time.time() for i in xrange(3,primeRange,2): if(reduce(lambda x,y:x and y,[i % p != 0 for p in primes])): primes.append(i) print "Using map-reduce: ", time.time() - start, " seconds"The results for primeRange = 100000:
Using map-reduce: 54.1150000095 seconds Using C++-style: 4.62000012398 secondsThe 2nd case makes the code more compact, but the condition will be evaluated for the entire list and then reduced to True / False. Is there a way to avoid that?
最满意答案
您可以将all用于生成器表达式:
if all(i % p != 0 for p in primes)生成器表达式将一次懒惰地评估一个术语,如果它达到不满足条件的值,则all术语将提前返回。
You could use all with a generator expression:
if all(i % p != 0 for p in primes)The generator expression will lazily evaluate one term at a time, and all will return early if it hits a value that doesn't satisfy the condition.
更多推荐
发布评论