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

前端 未结 30 2518
南旧
南旧 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:52
    reduce(lambda x, y : y + x, "hello world")
    
    0 讨论(0)
  • 2020-11-30 19:52

    This is a way to do it with a while loop:

    def reverse(s):
        t = -1
        s2 = ''
        while abs(t) < len(s) + 1: 
            s2 = s2 + s[t]
            t  = t - 1
        return s2
    
    0 讨论(0)
  • 2020-11-30 19:53

    This is a very interesting question, I will like to offer a simple one liner answer:

    >>> S='abcdefg'
    >>> ''.join(item[1] for item in sorted(enumerate(S), reverse=True))
    'gfedcba'
    

    Brief explanation:

    enumerate() returns [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')]. The indices and the values. To reverse the values, just reverse sort it by sorted(). Finally, just put it together back to a str

    0 讨论(0)
  • 2020-11-30 19:53
    def reverse(text):
        a=""
        l=len(text)
        while(l>=1):
            a+=text[l-1]
            l-=1
        return a
    

    i just concatenated the string a with highest indexes of text (which keeps on decrementing by 1 each loop).

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

    Today I was asked this same exercise on pen&paper, so I come up with this function for lists:

    def rev(s):
      l = len(s)
      for i,j in zip(range(l-1, 0, -1), range(l//2)):
        s[i], s[j] = s[j], s[i]
      return s
    

    which can be used with strings with "".join(rev(list("hello")))

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

    You can simply reverse iterate your string starting from the last character. With python you can use list comprehension to construct the list of characters in reverse order and then join them to get the reversed string in a one-liner:

    def reverse(s):
      return "".join([s[-i-1] for i in xrange(len(s))])
    

    if you are not allowed to even use negative indexing you should replace s[-i-1] with s[len(s)-i-1]

    0 讨论(0)
提交回复
热议问题