1

我是python的初学者,正在编写一个程序来计算素数直到给定N。这是我的代码。我看到的是,我调用numbers的列表在每次迭代后通过 for 循环进行了更改。但是,我看到我正在迭代的列表仍然包含对旧值的引用,而这个列表是用 for 循环更改的。请看下面的输出。

def getprimes(n):
         numbers = [ i for i in range (2,n+1)]
         primes=[]
         print "numbers in the beginning",numbers

         for i in numbers:
                print i
                primes.append(i)
                print "primes",primes
                print "numbers",numbers
                numbers=[k for k in numbers if (k%i!=0)]

         print "numbers at end",numbers
         return primes


print getprimes(10)

我的输出如下:

numbers in the beginning [2, 3, 4, 5, 6, 7, 8, 9, 10]
2
primes [2]
numbers [2, 3, 4, 5, 6, 7, 8, 9, 10]
3
primes [2, 3]
numbers [3, 5, 7, 9]
4
primes [2, 3, 4]
numbers [5, 7]
5
primes [2, 3, 4, 5]
numbers [5, 7]
6
primes [2, 3, 4, 5, 6]
numbers [7]
7
primes [2, 3, 4, 5, 6, 7]
numbers [7]
8
primes [2, 3, 4, 5, 6, 7, 8]
numbers []
9
primes [2, 3, 4, 5, 6, 7, 8, 9]
numbers []
10
primes [2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers []
numbers at end []
[2, 3, 4, 5, 6, 7, 8, 9, 10]

欢迎任何建议和意见!谢谢

4

3 回答 3

2

尝试编写简单直接的代码。过于复杂总是导致混乱。您的算法可以转换为两行函数。

>>> def getprimes(n):
         numbers = [ i for i in range (2,n+1)]
         primes=[k for k in numbers if all((k%i!=0) for i in numbers if i!=k)]
         return primes

>>> print getprimes(10)
[2, 3, 5, 7]

>>> print getprimes(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
于 2013-08-27T02:05:06.567 回答
2

重新绑定名称不会更改被迭代的可迭代对象。考虑重写代码以使用 while 循环。

于 2013-08-27T01:36:21.463 回答
1

试试这个,正如 Ignacio 所建议的那样,尝试使用 while 循环

def getprimes(n):
     numbers = [ i for i in range (2,n+1)]
     primes=[]

     while (numbers):
        print numbers[0]
        primes.append(numbers[0])
        print "primes",primes
        numbers=[k for k in numbers if k%numbers[0]!=0 ]
        print numbers

     print numbers
     return primes
于 2013-08-27T03:53:21.093 回答