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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…