在数列上附加数字的Python

2024-05-20 20:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码,我需要做一个素数列表,但我不知道为什么我的程序不附加素数列表。谢谢

n = int(input(""))
L = []
x = 0
c = 0

while x <= n - 1:
    Numero = int(input(""))
    for i in range(1, n + 1):
        if(n % i == 0):
            c += 1
    if c != 2:
        x += 1
    else:
        L.append(Numero)
        x += 1
print(L)

Tags: 代码in程序列表forinputifrange
1条回答
网友
1楼 · 发布于 2024-05-20 20:20:37

简短代码回顾:

while x <= n - 1:  # x < n is more comprehensive than x <= n-1
                   # Also, semantically it should be "for" loop
    # As DYZ mentioned, you need to reinitialize c at every iteration
    Numero = int(input("")) # I guess it's an error since you never use it
    for i in range(1, n + 1):  # it's ok to stop once c > 2
                               # also, you only need to check up to x/2
                               # and since we know it'll match 1 and x, 
                               #     whole loop can be replaced by all()
        if(n % i == 0):  # as DYZ mentioined, it should be x % i
            c += 1

    if c != 2:
        x += 1  # this statement is executed regardless of condition
    else:
        L.append(Numero)  # I guess you mean L.append(x)
        x += 1

在解决了所有这些问题之后,我们得到了如下结果:

for x in range(2, n+1):
    if all(x%i != 0 for i in range(2, x/2+1)):
        L.append(x)

或者,作为列表理解(请注意,现在我们只检查它是否可被发现的素数整除-复杂性的一个重大改进):

[L.append(x) for x in range(2, n+1) if all(x%i != 0 for i in L)]

对于n==22,我们得到:

>>> print L
[2, 3, 5, 7, 11, 13, 17, 19]

相关问题 更多 >