【问题标题】:Sieve of Eratosthenes pythonEratosthenes python 筛
【发布时间】:2014-11-25 18:28:16
【问题描述】:

我必须使用下面的来创建一个程序

create an empty list P to hold primes     
create a sieve list S of length n + 1. Set every element in S to True    
ITERATE over p from 2 to n  
    IF the element at p in S is True   
        add the element at p in S to P   
        generate multiples m of p up to n in increments of p   
             set the elements at all m in S to False   
return P

到目前为止,我已经生成了以下代码,但是当返回 P 时我得到一个空列表。 有什么想法吗?

def prime(n):
  P = []
  s = [n+1]
  s == True
  for p in range(2, n):
      if p in s == True:
          p.append(P)
          for m in range(p*p, n+1, p):
              m == False
  return P

【问题讨论】:

  • 作为旁注,你不需要说if p in s == True:,你可以说if p in s:
  • m == False 是一个表达式。也许你的意思是m = False
  • 您还将P(您的列表)附加到p(您的迭代器变量)。我假设你想要P.append(p)。一般来说,我建议使用更具描述性的名称,这样您就可以避免这个问题。
  • 所以我做了建议的修改,但返回时仍然得到一个空的 P 列表??

标签: python primes


【解决方案1】:

您没有创建s 来作为n+1 Trues 的列表;您创建了一个带有 one 元素的列表,n+1,然后询问它是否是 True(并忽略答案)。试试这个:

s = [True for x in xrange(n+1)]

您也从不s 做任何事,但一次只做一件事。

【讨论】: