Python在系列中附加数字

时间:2017-05-22 00:45:39

标签: 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)

1 个答案:

答案 0 :(得分:0)

简短的代码审核:

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]