Search code examples
pythonrecursionreturnnonetypesieve-algorithm

Recursive Sieve of Erasthotenes returning None


I implemented a recursive Sieve of Erasthotenes, which, from the debug statements used, appears to work, but returns None.

The code with the debug statements looks like this:

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

The function is (for instance) called with:

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

print(sieb2(lst, primes))

The output for this input looks like this:

# 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

From what I can see the function works as it should and goes into the else-statement with the return, the print-statement is executed properly too and outputs the final container.

Why does the return-statement output a NoneType and not the container list?


Solution

  • You're just missing one return statement from your recursive function:

    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
    

    Always remember to return the functions which you're calling recursively so that their values get correctly returned to the stack.