How would you define a recursive function that asks the user for a string and prints it from the outside in. For example, 123456 would print as 162534. Any help would be appreciated.

What do you have so far?

To start you are going index the first and last in the method.

str = '123456'
str[0]  #index the first
str[-1:]#index the last

Then just build a simple recursive method to solve.

Post your code if you have any more questions.

does it have to be recursive?
something like this (I haven't tested this code,
just typed it down really quickly)

def print_out_in(text):
    if len(text) % 2:
        end = ((len(text) - 1)/2) + 1
        for x in range(1,end):
            print text[x]
            print text[(-1)*x]
        print text[end+1]
    else:
        end = len(text)/2 + 1
        for x in range(1,end):
            print text[x]
            print text[(-1)*x]

Edited 6 Years Ago by jcao219: n/a

if it absolutely has to be recursive (which I hate):
here it is:

def outside_in(text):
    if len(text) <= 2:
        return text
    return (text[0] + text[-1]) + outside_in(text[1:-1])

I know there is a better way to write that last line,
but I'm too lazy to look into it

Edited 6 Years Ago by jcao219: n/a

I know there is a better way to write that last line,
but I'm too lazy to look into it

I think you could convert to a list and just pass a pair of index counters, but it is more than I want to do as well.

Edited 6 Years Ago by woooee: n/a

Thanks so much guys! Your help is greatly appreciated.

This question has already been answered. Start a new discussion instead.