Understanding recursive string reversal

前端 未结 2 1516
野的像风
野的像风 2021-01-27 16:35

I\'m using the Python Tutorial visualize webpage to try and understand the flow of this function that reverses a string:

text = \"hello\"
def reverse(text):
            


        
相关标签:
2条回答
  • 2021-01-27 16:57

    Here's the sequence of recursive calls, and what they return. You'll see that reverse("hello") returns the result of reverse("ello") plus "h".

    reverse("hello")
      --> return reverse("ello") + "h"
    

    So then the question is what does reverse("ello") return?

    reverse("ello")
      --> return reverse("llo") + "e"
    

    Continuing on...

    reverse("llo")
      --> return reverse("lo") + "l"
    
    reverse("lo")
      --> return reverse("o") + "l"
    

    Finally, it bottoms out when reverse("o") is called. Here len(text) <= 1, and so it returns simply "o".

    reverse("o")
      --> return "o"
    

    You can then work your way back up from bottom to top to calculate the return value from the original reverse("hello") call.

    0 讨论(0)
  • 2021-01-27 17:02
    reverse("hello")
    -> reverse("ello") + "h"
    -> reverse("llo") + "e" + "h"
    -> reverse("lo") + "l" + "e" + "h"
    -> reverse("o") + "l" + "l" + "e" + "h"
    -> "o" + "l" + "l" + "e" + "h"
    -> "olleh"
    

    This is to show the purpose of the return reverse(text[1:]) + text[0] line and its behaviour in action.

    0 讨论(0)
提交回复
热议问题