Reverse a string without using reversed() or [::-1]?

前端 未结 30 2583
南旧
南旧 2020-11-30 19:44

I came across a strange Codecademy exercise that required a function that would take a string as input and return it in reverse order. The only problem was you could not use

30条回答
  •  佛祖请我去吃肉
    2020-11-30 20:16

    You can also do it with recursion:

    def reverse(text):
        if len(text) <= 1:
            return text
    
        return reverse(text[1:]) + text[0]
    

    And a simple example for the string hello:

       reverse(hello)
     = reverse(ello) + h           # The recursive step
     = reverse(llo) + e + h
     = reverse(lo) + l + e + h
     = reverse(o) + l + l + e + h  # Base case
     = o + l + l + e + h
     = olleh
    

提交回复
热议问题