简体   繁体   English

如何从Python的递归函数返回列表?

[英]How to return a list from a recursive function in Python?

I have the following code: 我有以下代码:

def primes(n):
  acc = []
  return do_primes(range(2,n,1), acc)

def do_primes(xs, acc):
  if xs:
    head, tail = xs[0], xs[1:]
    acc.append(head)
    do_primes([x for x in xs if x % head != 0], acc)
  else:
    return acc

Invoking the code yields to None: 调用代码将输出为None:

>>> primes(10)
None

You need to return once more: 您需要再次return

def do_primes(xs, acc):
  if xs:
    head, tail = xs[0], xs[1:]
    acc.append(head)
    return do_primes([x for x in xs if x % head != 0], acc)
  else:
    return acc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM