Home > Software engineering >  Python: Print a list with recursion
Python: Print a list with recursion

Time:11-07

I have these two test cases:

calc1 = [['print', 5]] # 5
calc2 = [['print', 2], ['print', 4], ['print', 8]] # 2 4 8

And I can print them correctly with this function:

def exec_program(p):
    if len(p) == 1:
        print(p[0][1])
    else:
        for i in p:
            print(i[1])

print(exec_program(calc2))
>>> 2
>>> 4
>>> 8

But how can I solve this recursively? The number of items in calc can be 1 or many. All help appreciated

Edit: My current try. Looking for a solution

def exec_program(p):
    if len(p) == 1:
        print(p[0][1])
    else:
        print(exec_program[1:] - 1)

CodePudding user response:

def do_print(calc):
    if not calc:
       return
    if calc[0] == 'print':
        print(calc[1])
    else:
        for subcalc in calc:
            do_print(subcalc)

That will work for any depth of nested lists.

You will want to add some error checking on the inputs, better yet use some more strict data structure such as a NamedTuple.

CodePudding user response:

you can slice the list starting from the next element whenever you are done with printing an element, an example:

calc2 = [['print', 2], ['print', 4], ['print', 8]]
def print_me(calc2):
    if not calc2:
       return     #once calc2 is empty, we stop the recursion.
     print(calc2[0][1])
     return print_me(calc2[1::])
print_me(calc2)

CodePudding user response:

Are you wanting this?

lst = [['print', 2], ['print', 4], ['print', 8] ]# 2 4 8

def rec_print(lst):
    if not lst: return lst
    return([lst[0][1]]   rec_print(lst[1:]))

print(*rec_print(lst))

Output:2 4 8

  • Related