【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 才会通过。

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

转载于:https://www.cnblogs.com/alex-bn-lee/p/10523020.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值