简体   繁体   中英

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:

>>> primes(10)
None

You need to return once more:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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