python 从输入列表中获取双素数作为输出

u3r8eeie  于 2023-01-01  发布在  Python
关注(0)|答案(2)|浏览(148)

我想输入用空格分隔的数字作为输入,并把它们存储在一个列表中,我想把列表中所有的孪生素数作为输出,如果输入的数字中没有孪生素数,我想得到一个输出"No any twin primes"

  • 孪生素数-两个素数的差为2*

我的代码是这样的:

lst = input()
test_list =[]

for ele in lst.split():
    n_int = int(ele)
    test_list.append(n_int)

def prime(x):
    for k in range(2, x):
        if x%k == 0:
            return False
    return True

diff = 0
for i in test_list:
    for j in test_list:
        if prime(i) and prime(j):
            diff = abs(i-j)
        if diff == 2:
            print(i, j)
        
print("No any twin primes")

如果我输入一个像3 4 5 7 8这样的数列,我期望得到一个输出

3 5
5 7

但我的成果是

3 5
5 3
5 4
5 7
5 9
7 5
No any twin primes

如果在输入的列表(2 3 7 9)中没有任何孪生素数,我得到的预期输出为

No any twin primes

goqiplq2

goqiplq21#

所做更改:

(1)创建了res作为存储孪生素数的列表
(2)内部for循环的迭代是从i+1end

代码:-

lst = input("Enter the numbers: ")
test_list =[]

for ele in lst.split():
    n_int = int(ele)
    test_list.append(n_int)

def prime(x):
    for k in range(2, x):
        if x%k == 0:
            return False
    return True

diff = 0
res=[]
for i in range(len(test_list)):
    for j in range(i+1,len(test_list)):
        if prime(test_list[i]) and prime(test_list[j]):
            diff = abs(test_list[i]-test_list[j])
            if diff == 2:
                res.append([test_list[i],test_list[j]])
if res: 
    for i,j in res:
        print(i,j)
else:
    print("No any twin primes")

输出:-

Enter the numbers: 3 4 5 7 8
3 5
5 7

Enter the numbers: 2 3 7 9
No any twin primes
igetnqfo

igetnqfo2#

下面是我的尝试:

def twinPrimes(iter):
    primes = []
    res = []
    for i in iter:
        for j in range(2, int(i/2)+1):
            if i % j == 0:
                break
        else:
            primes.append(i)
    for i in range(len(primes)-1):
        if primes[i+1] - 2 == primes[i]:
            res.append((primes[i], primes[i+1]))
    if res == []:
        return "No any twin primes"
    else:
        return res
print(twinPrimes([3,5,7]))

您还可以更改返回打印,如下所示:

def twinPrimes(iter):
    primes = []
    res = []
    for i in iter:
        for j in range(2, int(i/2)+1):
            if i % j == 0:
                break
        else:
            primes.append(i)
    for i in range(len(primes)-1):
        if primes[i+1] - 2 == primes[i]:
            res.append((primes[i], primes[i+1]))
            print(primes[i], primes[i+1])
    if res == []:
        print("No any twin primes")

输入:twinPrimes([3,5,7])
输出:

3 5
5 7

输入:twinPrimes([2,5,9])
输出:

No any twin primes

相关问题