0

I am trying to create a script to reverse the order of a string and put a new character between each letter of the string. For example, let's say I have the word Difficulty, I would like it to be reversed, and a new character, such as a hyphen, added between each character.

Input: "Difficulty"

Output: "y-t-l-u-c-i-f-f-i-D"

The code I am I came up with adds an extra asterisk at the start of the script:

def try_reverse(s):
    if s == "":
        return s
    else:
        return try_reverse(s[1:]) +"-" + s[0]

Output: "-y-t-l-u-c-i-f-f-i-D"

The only catch is that it needs to be done as a recursion.

2
  • 1
    Change if s == "": return s to if len(s) <= 1: return s Commented Mar 27, 2020 at 19:28
  • That's brilliant. Didn't even think of that. Add it as the solution, and I will accept it. Commented Mar 27, 2020 at 19:31

1 Answer 1

2

You need to end the recursion where there is one letter left:

def try_reverse(s):
    if len(s) <= 1:
        return s
    else:
        return try_reverse(s[1:]) +"-" + s[0]
Sign up to request clarification or add additional context in comments.

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.