在列表中查找孪生素数并记录它们出现的顺序

时间:2016-08-26 16:22:35

标签: python

我正在研究一个程序,其目标是以某种方式分析孪生素数(孪生素数是(p,p + 2)形式的素数)。现在我有一个代码来计算%10形式的孪生素数余数。

这就是代码:

def twin_prime_counter_type10(n):
    not_prime = []
    prime = []
    A = range(n + 1)
    B = range(n + 1)
    for i in xrange(2, n+1):
        if i not in not_prime:
            prime.append(i)
            for j in xrange(i*i, n+1, i):
                not_prime.append(j)   
    for n,i in enumerate(prime):
        if not A[n] == prime[n]:
            A[i] = 1
    count1_3 = 0
    count7_9 = 0
    count9_1 = 0
    for i in B:
        if B[i] % 10 == 3 and B[i - 2] % 10 == 1:
            if A[i] * A[i-2] == 1:
                count1_3 += 1
        elif B[i] % 10 == 9 and B[i - 2] % 10 == 7:
            if A[i] * A[i-2] == 1:
                count7_9 += 1
        elif B[i] % 10 == 1 and B[i - 2] % 10 == 9:
            if A[i] * A[i-2] == 1:
                count9_1 += 1
    print count1_3
    print count7_9
    print count9_1

印刷筛(10000)

这部分代码工作正常,但我想知道是否有人知道一种方式,当我找到(1)的(孪生素数)对时,我也可以记录它们出现在列表中的顺序。我不需要任何人实际编写执行此操作的代码,我只是想知道是否有人知道python中的内置工具,我可以使用它来执行此任务。

感谢您的帮助。

1 个答案:

答案 0 :(得分:-1)

假设sieveSieve of Eratosthenessimilar,那么您可以使用pairwise模块中的itertools配方来仅获取孪生素数使用生成器表达式

from itertools import tee #, izip # <-- for python 2

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b) #izip(a, b) # <-- for python 2

def twin_primes(n):
    return ( (p1,p2) for p1,p2 in pairwise(sieve(n)) if p1+2 == p2 )
    # or use list comprehension, but I prefer generator as they use 
    # less memory and can be infinite, as sieve can be made to be 
    # infinite as well

例如

>>> print( list(twin_primes(100)) )
[(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), (59, 61), (71, 73)]
>>>

同样你可以将它与enumerate一起使用来获得该对中与素数列表相关的第一个素数的索引,例如

>>> primes=list(sieve(100))
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]   
>>> twins=[ (i,pair) for i,pair in enumerate( pairwise(primes) ) if pair[0]+2 == pair[1] ]
>>> twins
[(1, (3, 5)), (2, (5, 7)), (4, (11, 13)), (6, (17, 19)), (9, (29, 31)), (12, (41, 43)), (16, (59, 61)), (19, (71, 73))]
>>> primes[1]
3
>>> primes[4]
11
>>> primes[9]
29
>>>