0

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.

4
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by jozz3
0

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.

0

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 by jcao219: n/a

0

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 by jcao219: n/a

0

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 by woooee: n/a

0

Thanks so much guys! Your help is greatly appreciated.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.