Python reversing a string using recursion

前端 未结 6 637
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 23:34

I want to use recursion to reverse a string in python so it displays the characters backwards (i.e \"Hello\" will become \"olleh\"/\"o l l e h\".

I wrote one that do

6条回答
  •  余生分开走
    2020-12-15 00:05

    I just want to add some explanations based on Fred Foo's answer. Let's say we have a string called 'abc', and we want to return its reverse which should be 'cba'.

    def reverse(s):
        if s == "":
            return s
        else:
            return reverse(s[1:]) + s[0]
       
                 
    s = "abc"
    print (reverse(s)) 
    

    How this code works is that: when we call the function

    reverse('abc')                       #s = abc
    =reverse('bc') + 'a'                 #s[1:] = bc    s[0] = a
    =reverse('c') + 'b' + 'a'            #s[1:] = c     s[0] = a
    =reverse('') + 'c' + 'b' + 'a'
    ='cba'
    

提交回复
热议问题