Eratosthenes 的递归筛法返回 None

Recursive Sieve of Erasthotenes returning None

我实现了 Erasthotenes 的递归筛选,从使用的调试语句来看,它似乎可以工作,但是 returns None.

带有调试语句的代码如下所示:

def sieb2 (iterable, container):
    print("Just called:", iterable, container, '\n')
    if len(iterable) != 1:
        container.append(iterable [0])
        iterable = [item for item in iterable if item % iterable [0] != 0]
        print("New call:", iterable, container, '\n')
        sieb2(iterable, container)
    else: 
        container.append(iterable[0])
        print("Return:", iterable, container, '\n')
        print("Container:", container)
        return container

该函数(例如)调用方式:

lst = list(range(2, 10) # I might add statements for removing everything <2 and sorting
primes = []

print(sieb2(lst, primes))

此输入的输出如下所示:

# Debug-Statements from the function:
Just called: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [] 

New call: [3, 5, 7, 9, 11, 13, 15, 17, 19] [2] 

Just called: [3, 5, 7, 9, 11, 13, 15, 17, 19] [2] 

New call: [5, 7, 11, 13, 17, 19] [2, 3] 

Just called: [5, 7, 11, 13, 17, 19] [2, 3] 

New call: [7, 11, 13, 17, 19] [2, 3, 5] 

Just called: [7, 11, 13, 17, 19] [2, 3, 5] 

New call: [11, 13, 17, 19] [2, 3, 5, 7] 

Just called: [11, 13, 17, 19] [2, 3, 5, 7] 

New call: [13, 17, 19] [2, 3, 5, 7, 11] 

Just called: [13, 17, 19] [2, 3, 5, 7, 11] 

New call: [17, 19] [2, 3, 5, 7, 11, 13] 

Just called: [17, 19] [2, 3, 5, 7, 11, 13] 

Mew call: [19] [2, 3, 5, 7, 11, 13, 17] 

Just called: [19] [2, 3, 5, 7, 11, 13, 17] 

Return: [19] [2, 3, 5, 7, 11, 13, 17, 19] 

Container: [2, 3, 5, 7, 11, 13, 17, 19]

# Printed return:

None

据我所见,该函数正常工作,并使用 return 进入 else 语句,打印语句也正确执行并输出最终容器。

为什么 return 语句输出 NoneType 而不是容器列表?

您只是在递归函数中遗漏了一个 return 语句:

def sieb2(iterable, container):
    print("Just called:", iterable, container, '\n')
    if len(iterable) != 1:
        container.append(iterable[0])
        iterable = [item for item in iterable if item % iterable[0] != 0]
        print("New call:", iterable, container, '\n')
        return sieb2(iterable, container)  # FIXED
    else: 
        container.append(iterable[0])
        print("Return:", iterable, container, '\n')
        print("Container:", container)
        return container

永远记住 return 递归调用的函数,以便它们的值正确返回到堆栈。

def sieb2 (iterable, container):
    print("Just called:", iterable, container, '\n')
    if len(iterable) != 1:
        container.append(iterable [0])
        iterable = [item for item in iterable if item % iterable [0] != 0]
        print("New call:", iterable, container, '\n')

        # Added return
        return sieb2(iterable, container)
    else: 
        container.append(iterable[0])
        print("Return:", iterable, container, '\n')
        print("Container:", container)
        return container

lst = list(range(2, 10)) # I might add statements for removing everything <2 and sorting
primes = []

r = sieb2(lst, primes)
print('r ', r)

更新内容:
return sieb2(iterable, container)