pythonfunctionrecursiontrace

Tracing a recursive function


i have a homework assignment listed below

Lee has discovered what he thinks is a clever recursive strategy for printing the elements in a sequence (string, tuple, or list). He reasons that he can get at the first element in a sequence using the 0 index, and he can obtain a sequence of the rest of the elements by slicing from index 1. This strategy is realized in a function that expects just the sequence as an argument. If the sequence is not empty, the first element in the sequence is printed and then a recursive call is executed. On each recursive call, the sequence argument is sliced using the range 1:. Here is Lee’s function definition:

and the code I have so far, but it really just makes the function print what I test:

def printAll(seq):
    if seq:
        print(seq[0])
        printAll(seq[1:])


test_string = "Run it up plenty"
test_tuple = ("tony", "boney", "phoney")
test_list = ["yuji", "megumi","nobara"]
printAll(test_list)

the assignment wants:

Write a program that tests this function and add code to trace the argument on each call. Does this function work as expected? If so, are there any hidden costs in running it?

I do not like essentially having to ask the straight question from homework, but I do not understand at all how to get the function to be traced for the assignment. I do not even know where to start here.


Solution

  • If you want to track both the value of the sequence (as you already do) and the recursion depth, then it is indeed nice to use indentation (as you suggested yourself in comments).

    You can pass the current indentation as a second argument, which has a default value for when the top-level call is made:

    def printAll(seq, indent=""):
        if seq:
            print(f"{indent}{seq[0]}")  # print the value with indentation
            printAll(seq[1:], indent + ". ")  # extend the indentation
    

    For your example call, this outputs:

    yuji
    . megumi
    . . nobara
    

    This illustrates that there is a cost in terms of memory, more specifically, stack space. For a sequence of 3 items this is negligible, but if your sequence has 10,000 elements, your recursion depth would also go to 10,000 and your Python configuration might not allow for using so much stack space.

    NB: I used f-string syntax, which is a nicer way to do the following:

            print(indent + str(seq[0]))