Casper Ne
Casper Ne

Reputation: 23

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

Upvotes: 1

Views: 329

Answers (3)

Selcuk
Selcuk

Reputation: 59228

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:])

Upvotes: 0

mzndr
mzndr

Reputation: 91

Doesn't this function produce the result you want?

def print_list(n_list):
    for item in n_list:
        print(item)

I'm not sure why exacly you only try to iterate over half the list half = len(n_list) // 2?

Upvotes: 0

Steven Rumbalski
Steven Rumbalski

Reputation: 45541

n_list = ['hi', [22,45], 'dog', 21]
print(*n_list, sep='\n')

gives

hi
[22, 45]
dog
21

Upvotes: 3

Related Questions