Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hello I think the two snippet below should essentially do the same thing:

for divisor in range(2, 21):
    if sample % divisor != 0:
        break

The first snippet, I use sample divided by number from 2 to 20, if any one of them gives remainder != 0, then I will break and try sample += 1 (codes omitted)

if all(sample % divisor == 0 for divisor in range(2, n2+1)):
    return sample

The second snippet I will return the sample if all() comes back with True, otherwise I will try sample += 1 (codes omitted)

The second snippet is found twice slower than the first one. I don't understand, when python evaluate all(), if one False was found in iteration, it should immediately comes back False for all(), instead of finish the whole iteration, right?

So why is the second snippet slower than the first one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's your hint:

>>> (sample % divisor == 0 for divisor in range(2, n2+1))
<generator object <genexpr> at 0x10ead7a00>

Your code is creating a genexp, and requiring all to call the next method on that genexp over and over.

This has an unavoidable performance penalty over a for loop involving no function calls. See also Python: Why is list comprehension slower than for loop


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...