反转字符串而不使用反转()或[:: - 1]? [英] Reverse a string without using reversed() or [::-1]?

查看:202
本文介绍了反转字符串而不使用反转()或[:: - 1]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的Codecademy练习,它需要一个函数,将一个字符串作为输入,并以相反的顺序返回。唯一的问题是你不能使用颠倒的方法或常用的答案在这里stackoverflow, [:: - 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆