使用Map

编程入门 行业动态 更新时间:2024-10-24 14:18:50
使用Map-Reduce时Python中的延迟布尔评估(Lazy boolean evaluation in Python when using Map-Reduce)

我将使用我的例子:我想用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 seconds

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

更多推荐

本文发布于:2023-04-29 13:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336292.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!