【378】python 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 才会通过。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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:\n' ) # 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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步