user3053024
user3053024

Reputation: 47

Python- recursion with printing

I need to print the elements of list, such that if an element is 100 or greater, it's followed by a newline, and if not, it's followed by a space.

This is what I have so far:

def function(list):
    if list == []:
        return None
    elif list[0] >= 100:
        print(list[0], function(list[1:]), end = '\n')
    else:
        print(list[0], function(list[1:]), end = '')
    return None

But when I try list = [2,3,103, 8, 10], Python prints:

10 None8 None103 None

3 None2 None

Any suggestions/help?

Upvotes: 1

Views: 1599

Answers (3)

rlms
rlms

Reputation: 11060

You're on the right track. This is what you want:

def function(lst):
    if not lst:
        return
    elif lst[0] >= 100:
        print(lst[0], end='\n')
    else:
        print(lst[0], end=' ')
    function(lst[1:])

(I renamed list to lst because list is a builtin type that we don't want to overwrite).

Explanation: if we have the recursive call inside the print call, we print the return value of the function, which is always going to be None, as it never returns anything else. So we have to move it outside.

Also, the boolean value of an empty list is False, so we can replace lst == [] with not lst, as recommended by PEP 8.

Upvotes: 1

Steve Barnes
Steve Barnes

Reputation: 28370

list is a reserved word.

myList = [2,3,103, 8, 10]
for i in myList:
   print(i, end = (i>=100) and '\n' or ' ')

Upvotes: 1

kalhartt
kalhartt

Reputation: 4129

After your function exists it returns None, which is why your print statements have the "None" in them. Just move the recursive call outside of print

    elif list[0] >= 100:
        function(my_list[1:])
        print(my_list[0], end='\n')
    else:
        function(my_list[1:])
        print(my_list[0], end='')

Upvotes: 0

Related Questions