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

前端 未结 30 2550
南旧
南旧 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 19:59

    Blender's answer is lovely, but for a very long string, it will result in a whopping RuntimeError: maximum recursion depth exceeded. One might refactor the same code into a while loop, as one frequently must do with recursion in python. Obviously still bad due to time and memory issues, but at least will not error.

    def reverse(text):
        answer = ""
        while text:
            answer = text[0] + answer
            text = text[1:]
        return answer
    

提交回复
热议问题