【问题标题】:Recursions to produce the prime numbers in Python 2在 Python 2 中产生质数的递归
【发布时间】:2017-05-19 12:07:24
【问题描述】:

我试图在 python 中使用递归来生成素数(因为我发现迭代方法会花费太多时间,特别是如果说想要找到所有素数,比如 100 万或所以)。这是我的代码:

def primes(n): #to produce prime numbers less than or equal to n
    if n <= 1:
        return "No primes that satisfy"
    elif n == 2:
        return [2]
    else:
        if all(n%a != 0 for a in primes(n-1)): #A number, n, must not be divisible by any of the prime numbers contained in the list primes(n-1)
          k = primes(n-1).append(n)
          return k
        else:
          S = primes(n-1)
          S = primes(n)
          return S
print primes(5)

我收到以下错误 - TypeError:'NoneType' object is not iterable。我只是 Python 的初学者,我不确定这意味着什么。如果有人能指出为什么会出现此错误以及我可以对程序进行哪些改进以避免此错误,我将不胜感激。 谢谢

【问题讨论】:

  • 我意识到我没有在代码的“if all”部分声明 primes(n)。但是,如果我输入“k = primes(n)”,我会遇到“RuntimeError: maximum recursion depth exceeded”以及为函数调用赋值的问题。
  • 这种递归算法似乎随着时间呈指数增长。对我来说,primes(15) 需要 0.02 秒,primes(20) 需要 0.2 秒,而 primes(25) 需要 6.4 秒。所以每个 +5 至少需要 *10 更长的时间。仅供参考:en.wikipedia.org/wiki/Sieve_of_Eratosthenes
  • 看来埃拉托色尼筛法是生成素数的最佳方法?
  • 绝对是老好方法,甚至没有什么改进。

标签: python recursion primes nonetype


【解决方案1】:

考虑这个程序片段:

k = primes(n-1).append(n)
return k

list.append() 的返回值是None,所以k = None,你有效地执行了return None

试试这个:

k = primes(n-1) + [n]

除此之外:OP 至少还有一个其他错误。他们需要删除S = primes(n)这一行

【讨论】:

  • 感谢您的及时回复。是的,这种方法确实有效,但是对于较小的 n 值,例如 n = 3。当我测试“primes(5)”时,它会遇到运行时错误:“超出最大递归深度”。有什么办法可以避免这种情况吗?谢谢。
  • 修复您的其他错误。删除S = primes(n)这一行
猜你喜欢
  • 2010-09-07
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多