问题描述
我遇到了一个奇怪的 Codecademy 练习,它需要一个将字符串作为输入并以相反顺序返回它的函数.唯一的问题是你不能在 stackoverflow 上使用反向方法或常见答案,[::-1]
.
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 the reversed method or the common answer here on stackoverflow, [::-1]
.
显然在现实的编程世界中,人们很可能会选择 extended slice 方法,甚至使用 reversed
函数,但也许在某些情况下这不起作用?
Obviously in the real world of programming, one would most likely go with the extended slice method, or even using the reversed
function but perhaps there is some case where this would not work?
我在下面以问答的形式提供了一个解决方案,以防将来对人们有所帮助.
I present a solution below in Q&A style, in case it is helpful for people in the future.
推荐答案
你也可以用递归来实现:
You can also do it with recursion:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
以及字符串 hello
的简单示例:
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
这篇关于不使用 reversed() 或 [::-1] 来反转字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!