Python中的反向字符串函数(原始步骤)

时间:2013-10-11 19:53:00

标签: python

我尝试了一种不使用[::?]方法来执行反向字符串功能的方法。我是编码的新手,我只是尝试使用“原始”步骤。以下是我的功能和规格。我想知道这是否是编写函数的有效方法。我感谢任何帮助。谢谢!

def reverse(word):
    x = -2                     #word in reversed order counter
    y = 1                      #starts counter to end "while" statement below
    reversed = word[-1]        #starts the reversed-word at last letter of word
    while len(word) > y:       #ending parameter for when all letters run through loop
        reversed += word[x]    #adds letters to reversed word starting at word[-2]
        x -= 1                 #moves position in word 1 to the left
        y += 1                 #increases the counter by 1
return reversed

2 个答案:

答案 0 :(得分:1)

添加到字符串很慢。最好以相反的顺序列出字符串中的字符列表,然后在其上使用字符串方法join

示例代码(非常接近原始函数):

def reverse(word):
    index = len(word)-1                  
    result = []      
    while index >= 0: 
        result.append(word[index]) 
        index -= 1 
    return "".join(result)

更好的示例代码:

def reverse(word):
    word_list = []
    for i in range(len(word)-1, -1, -1):
        word_list.append(word[i])
    return "".join(word_list)

def reverse(word):
    return "".join(word[i] for i in range(len(word)-1, -1, -1))

更好的代码:

def reverse(word):
    return "".join(reversed("abc"))

def reverse(word):
    return word[::-1]

但是,当然,效率最高的代码是字符最少的代码。 [/讽刺]

reverse =lambda s:s and s[-1]+reverse(s[:-1])or s

另一种解决方案(我认为它可能很慢):

def reverse(word):
    word_list = []
    for i in word:
        word_list.insert(0, word[i])
    return "".join(word_list)

答案 1 :(得分:1)

我喜欢功能性的递归方式,但这可能不适合Python:

def rev(w): 
    return rev(w[1:]) + w[0] if w else w

您希望包含类型检查或其他内容,或者可能需要对此进行扩展以处理任何可迭代而不仅仅是字符串。

相关问题