反转字符串而不使用反转()或[:: - 1]? [英] Reverse a string without using reversed() or [::-1]?
问题描述
[:: - 1]
。 显然在编程的现实世界中,最有可能的是与扩展切片方法,甚至使用颠倒的
函数,但也许有些情况下这不会工作?
我在下面的Q& A风格中提出了一个解决方案,以防对将来的人有所帮助。
def reverse(text):
if len文本)< = 1:
返回文本
返回反向(text [1:])+ text [0]
$ b $ 以下是一个简单的例子: hello
:
reverse(hello)
= reverse(ello)+ h#递归步骤
= rev erse(llo)+ e + h
= reverse(lo)+ l + e + h
= reverse(o)+ l + l + e + h#Base case
= o + l + l + e + h
= olleh
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]
.
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]
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
这篇关于反转字符串而不使用反转()或[:: - 1]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!