0

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)
2
  • 1
    Please update your question with the code you have tried. Commented Nov 6, 2022 at 19:32
  • Have you tried your recursive version? Does it produce the right output? Are there any errors? Commented Nov 6, 2022 at 19:40

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution, you took the first element of every list in account, assuming that it might change from print to a different functionality.
0

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)

2 Comments

Agreed, I meant this to soften my critique, not to add more critique. However, on closer inspection OP might mean a different kind of recursion (on depth of nested lists, not on list length).
I will agree with you on this, however it is not clarified why is the op having a nested list for printing elements, so we don't know the goal behind this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.