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

前端 未结 30 2519
南旧
南旧 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:54

    Pointfree:

    from functools import partial
    from operator import add
    
    flip = lambda f: lambda x, y: f(y, x)
    rev = partial(reduce, flip(add))
    

    Test:

    >>> rev('hello')
    'olleh'
    
    0 讨论(0)
  • 2020-11-30 19:55
    def reverse(s):
        return "".join(s[i] for i in range(len(s)-1, -1, -1))
    
    0 讨论(0)
  • 2020-11-30 19:55

    You've received a lot of alternative answers, but just to add another simple solution -- the first thing that came to mind something like this:

    def reverse(text):
        reversed_text = ""   
    
        for n in range(len(text)):
            reversed_text += text[-1 - n]
    
        return reversed_text
    

    It's not as fast as some of the other options people have mentioned(or built in methods), but easy to follow as we're simply using the length of the text string to concatenate one character at a time by slicing from the end toward the front.

    0 讨论(0)
  • 2020-11-30 19:55

    Here's my contribution:

    def rev(test):  
        test = list(test)
        i = len(test)-1
        result = []
    
        print test
        while i >= 0:
            result.append(test.pop(i))
            i -= 1
        return "".join(result)
    
    0 讨论(0)
  • 2020-11-30 19:57

    All I did to achieve a reverse string is use the xrange function with the length of the string in a for loop and step back per the following:

    myString = "ABC"
    
    for index in xrange(len(myString),-1):
        print index
    

    My output is "CBA"

    0 讨论(0)
  • 2020-11-30 19:58
    def reverseThatString(theString):
        reversedString = ""
        lenOfString = len(theString)
        for i,j in enumerate(theString):
            lenOfString -= 1
            reversedString += theString[lenOfString]
        return reversedString
    
    0 讨论(0)
提交回复
热议问题