0

I'm trying to make a recursion sequence (Have to do it like this) where I print a * followed by the last character plus the following character on the next line, etc. So if "Hello" was passed, it would print:

*
o
ol
oll
olle
olleH

My question is, how do I get the last character to stay and how do I get the star to print first. I have it so everything prints in reverse, but only one character and the star prints last. This is what I have:

def reverse(s):
    if len(s) == 0:
        return ('*')
    else:
        print(s[-1])
        return reverse(s[0:-1])

Thanks!

3 Answers 3

2

Try this:

def reverse(s):
    if len(s) == 0:
        print(*)
    else:
        reverse(s[1:])
        print(s[::-1])

When the string has no length it will print *, otherwise it will recursively call with 1 less character and print the string reversed.

As a traceback of reverse('two'):

Call - 'two'
 Call - 'wo'
  Call - 'o'
   Call - ''
    Print - '*'
    Return
   Print - 'o'
   Return
  Print - 'ow'
  Return
 Print - 'owt'
 Return

Call as reverse('Hello')

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you for the explanation as well!
0

this will print:

olleh
olle
oll
ol
o
*

output=[]
def reverse(s):
    if (len(s)>0):
        print(s[::-1])
        output.append(s[::-1])
        reverse(s[1:])
    else:
        print('*')
        output.append('*')

reverse('hello')        
# if you do need the original order, see below
for e in (output[::-1]):
    print(e)     

Comments

0

Recursive version:

def reverse(s, length, iteration):
    if iteration == 0:
        return '*' + reverse(s, length, iteration+1)
    elif iteration == length:
        return s[::-1]
    else:
        return '%s\n' % s[length - iteration: length][::-1] + reverse(s, length, iteration+1)

input = 'Hello'
print(input, len(input), 0)

Generator version

def reverse(s):
    print('*')
    length = len(s)
    for i in range(1, length + 1):
        yield s[length - i: length][::-1]


print('\n'.join(list(reverse('Hello'))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.