0

For a homework assignment I have to create a recursive function that reverses a string. Here's what I have currently. The last three lines of code were made by the instructor and we aren't allowed to change them. When I run the program, nothing is returned. I think the code to reverse the string is correct, but I'm trying to figure out how to print the result.

def reverse(input_string):
    if len(input_string) == 0:
         return input_string
    else:
         return reverse(input_string[1:]) + input_string[0]

print "Please enter the string you want to reverse: "
initial_input = raw_input()

reverse(initial_input)
2
  • Are you sure you can't change the last line? Your logic seems correct, but you need to print the result of reverse somehow. Commented Sep 23, 2013 at 3:36
  • The instructions of the assignment were not to change anything in the last three lines, but I can't think of any other way to do it. I added a print in front of the final reverse(initial_input) and it works. Commented Sep 23, 2013 at 3:37

8 Answers 8

3

you need to print the return

so reverse(initial_input) is assigned to the returned value but if you wanted it printed you need to do `print reverse(initial_input)

since you cant change the last three you should print withing the function instead of returning it. your instuctor probably wanted you to do this to show the recursion

Here ya go try this its a little more complicated but it reverses in the function:

def reverse(text):
    lst = []
    for i in range(0,len(text)):

        lst.append(text[len(text)-(i+1)])

    lst = ''.join(lst)
    print lst

print "Please enter the string you want to reverse: "
initial_input = raw_input()

reverse(initial_input) 
Sign up to request clarification or add additional context in comments.

6 Comments

There's also a missing ) on the second (first) line of the function
I added that to my answer too
I left out at the last parenthesis when I typed my code up on here, so that wasn't causing me a problem. When I try to print within my function (replacing the returns with prints), I get this error:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Oh ok i see you might need to take a differnt approach if you cant change the last three lines
|
2

Sounds like you just need to print the reversed string in the function? Did you instructor provide an actual example of what the output should look like?

Perhaps you should define a separate function to do the reverse, and have the reverse function simply call this new function, and print the result.

def actual_reverse(input_string):
    if len(input_string) == 0:
         return input_string
    else:
         return actual_reverse(input_string[1:]) + input_string[0]

def reverse(input_string):
    print actual_reverse(input_string)

print "Please enter the string you want to reverse: "
initial_input = raw_input()

reverse(initial_input)

Comments

1

Based on the formulation of the problem, i would assume that your instructor would run this code not from file, but within interactive shell. So, feel free to add print operator before last code line (call of recursive function) in interest of debugging, and do not forget to delete it afterwards.

You can test your code in interactive shell yourself simply running python in console. Notice that if you would copy-paste your program at once, empty line after raw_input() would go as initial_input value. Just copy-paste up to and including line with raw_input, enter your string and then call reverse(initial_input).

Much simpler way is to call python -i your_source.py, and call reverse(initial_input). Just consider here that reverse(initial_input) would actually run twice (which is not a problem here).

Comments

0
def reverse(input_string):
    if len(input_string) == 0:
        return input_string
    else:
        return reverse(input_string[1:]) + input_string[0]

print ("Please enter the string you want to reverse: ")
initial_input = input()
print(reverse(initial_input))

Comments

0

In addition to what everyone else has said, you can do the same recursion from your sample code except in reverse. Doing it in reverse would allow you to print each character as it travels through the function.

def reverse(input_string):
    if len(input_string) == 1:
        print input_string[len(input_string) - 1]
        return input_string
    else:
        print input_string[len(input_string) - 1]
        return input_string[len(input_string) - 1] + reverse(input_string[:len(input_string) - 1])

print "Please enter the string you want to reverse: "
initial_input = raw_input()

reverse(initial_input)

It's definitely not as readable, but it allows you to print out the reverse without changing the last three lines.

Comments

0

You could always add a second parameter with a default value to indicate if you need to print the result or not:

def reverse(input_string, p=True):
    if len(input_string) == 0:
        return input_string
    r = reverse(input_string[1:], False) + input_string[0]
    if p == True:
        print(r)
    return r

Or assuming that you don't need to print a newline you could just print a character at a time:

def reverse(input_string):
    if len(input_string) == 0:
        return input_string
    r = reverse(input_string[1:]) + input_string[0]
    print(input_string[0], end='')  # version 3 print 'print input_string[0],' in version 2.X
    return r

Comments

0

Here is another recursive solution:

def reverString(data, i):
  if (len(data) + i) == 0:
    return data[0]
  else:
    return data[i] + reverString(data, i-1)

data = 'I am doing great'

print(reverString(data, -1))

Console's output: taerg gniod ma I

Comments

0

simply

def rev_str(s):
    if len(s)==0:
        return ""
    
    sts=s.split(" ")[0]

    return "".join(sts[::-1])+ " "+rev_str(s[len(sts)+1:])

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.