简体   繁体   中英

Need help understanding a recursive solution to reverse a List

How does this recursive solution work step by step. I'm having trouble understanding what is happening to the string and the indexes each time a return happens in the function. Thanks

s = 'string'
def rreverse(s):
    if s == '':
        return s
    else:
        return rreverse(s[1:]) + s[0]

print(rreverse(s))
return rreverse(s[1:]) + s[0]

This line takes the substring of s from the second character (index 1) to the end, reverses it recursively and then adds the first character (index 0) to it. This way the whole string gets reversed. The recursion obviously ends when the string is empty. For the input string

"abcd" 

the recursion would go like this:

abcd
rreverse(bcd) + a
(rreverse(cd) + b) + a
((rreverse(d) + c) + b) + a
(((rreverse('') + d) + c) + b) + a
'' + d + c + b + a
d + c + b + a
dc + b + a
dcb + a
'dcba'

Then you need to learn basic debugging: trace the program and watch. Here's a simple version.

s = 'string'
def rreverse(s):
    print "ENTER", s
    if s == '':
        return s
    else:
        result = rreverse(s[1:]) + s[0]
        print "RETURN", s, result
        return result

print(rreverse(s))

If you're having trouble with the general concept of recursion, tracing a program is a good way to follow the process. You should also look through the various explanations on line and on this site. If none of those give you a good grasp of recursion, then update this question or post a new one with your specific points of confusion.

Output ... since I have the program right here:

ENTER string
ENTER tring
ENTER ring
ENTER ing
ENTER ng
ENTER g
ENTER 
RETURN g g
RETURN ng gn
RETURN ing gni
RETURN ring gnir
RETURN tring gnirt
RETURN string gnirts
gnirts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM