378python any() and all()

Posted alex_bn_lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了378python any() and all()相关的知识,希望对你有一定的参考价值。

Reference:

[1] Python all() - Python Standard Library  

[2] Python any() - Python Standard Library  

 

all() and any() 函数主要用于需要判断某个数组是不是都满足了某种条件,设置一个跟数组一样的 bool 数组,判断 bool 数组是否都为 True,或者有没有 True 等等。

 

Q:

Insert your code into consecutive_primes.py so as to find all sequences of 6 consecutive prime 5-digit numbers, say (a,b,c,d,e,f), with b=a+2, c=b+4, d=c+6, e=d+8, and f=e+10. So a, b, c, d, e and f are all 5-digit prime numbers and no number between a and b, between b and c, between c and d, between d and e, and between e and f is prime.

If you are stuck, but only when you are stuck, then use consecutive_primes_scaffold.py.

 

A: by McDelfino,在这个程序中使用了 all() 函数用来判断是否对应的数为质数,如果都返回 True 才会通过。

from math import sqrt

def is_prime(n):
    if n%2 == 0: return False
    for i in range(3,round(sqrt(n))+1, 2):
        if n%i == 0:
            return False
    return True

print(‘The solutions are:
‘)
# The list of all even i‘s such that a + i is one of a, b, c, d, e, f.
good_leaps = tuple(sum(range(0, k, 2)) for k in range(2, 13, 2))

# Write a loop that generates all odd numbers a between 10_000 and 99_999 and tests whether
# for all i = 0, 2, 4, ..., 30, i is in good_leaps iff a + i is prime.
for a in range(10_001, 100_000-5, 2):
    if all([is_prime(a+i) for i in good_leaps]):
        tmp = [a+i for i in good_leaps]
        count = 0
        for j in range(tmp[1]+2, tmp[5], 2):
            if is_prime(j): count+=1
        if count == 3:
            print(*[a+i for i in good_leaps])
The solutions are:

13901 13903 13907 13913 13921 13931
21557 21559 21563 21569 21577 21587
28277 28279 28283 28289 28297 28307
55661 55663 55667 55673 55681 55691
68897 68899 68903 68909 68917 68927

以上是关于378python any() and all()的主要内容,如果未能解决你的问题,请参考以下文章

sql中any和all的区别?

SQL中 ALL 和 ANY 区别的

python中的any和all函数

Python-any函数和all函数

python中的any和all函数

[python] 之all()和any()内置函数