Search code examples
pythonpython-3.xrecursionreduction

How to print list vertically using recursion?


I want to print this list vertically recursively: Example:

print_list(['hi', [22,45], 'dog', 21])

Expected:

hi
[22, 45]
dog
21

Here is my code:

def print_list(n_list):
    if len(n_list) == 0:
            return
    else:
        half = len(n_list) // 2
        for i in range(half):
            if half == 2:
                print (n_list[i], sep = "\n")
        else:
            print (n_list[half+i])

Here is what I am getting:

hi
[22, 45]
dog

I am not sure why the list does not print in full. This also happens for lists with more items, only a portion shows. I know I am messing something out in the print statement but can't figure it out...


Solution

  • You are close, but you are not applying reduction as your function does not call itself. This is a slightly modified version of your code that should work:

    def print_list(n_list):
      if len(n_list) == 0:
        return
      else:
        half = (len(n_list) + 1) // 2
    
        # Print elements in the first half:
        for i in range(half):
          print(n_list[i])
    
        # Print second half using recursion:
        print_list(n_list[half:])