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

前端 未结 30 2522
南旧
南旧 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 20:12

    Just another option:

    from collections import deque
    def reverse(iterable):
        d = deque()
        d.extendleft(iterable)
        return ''.join(d)
    
    0 讨论(0)
  • 2020-11-30 20:14

    you have got enough answer.

    Just want to share another way.

    you can write a two small function for reverse and compare the function output with the given string

    var = ''

    def reverse(data):

    for i in data:
        var = i + var
    return var
    

    if not var == data :

    print "No palindrome"

    else :

    print "Palindrome"

    0 讨论(0)
  • 2020-11-30 20:15

    Inspired by Jon's answer, how about this one

    word = 'hello'
    q = deque(word)
    ''.join(q.pop() for _ in range(len(word)))
    
    0 讨论(0)
  • 2020-11-30 20:16

    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
    
    0 讨论(0)
  • 2020-11-30 20:16

    i just solved this in code academy and was checking my answers and ran across this list. so with a very limited understanding of python i just did this and it seamed to work.

    def reverse(s):
        i = len(s) - 1
        sNew = ''
        while  i >= 0:
            sNew = sNew + str(s[i])
            i = i -1
        return sNew
    
    0 讨论(0)
  • 2020-11-30 20:16

    Not very clever, but tricky solution

    def reverse(t):
        for j in range(len(t) // 2):
            t = t[:j] + t[- j - 1] + t[j + 1:- j - 1] + t[j] + t[len(t) - j:]
        return t
    
    0 讨论(0)
提交回复
热议问题