Reverse best solution?


#1



Hi,

Is this actually the simplest code yet?


def reverse(text):
    newstring = []
    for i in range(len(text)-1,-1,-1):
        newstring.append(text[i])
    newstring = ''.join(newstring)
    return newstring


#2

Wow yeah that looks way simpler than mine haha. This is mine:

def reverse(text):
a=[];
for j in range(0,len(text)):
a.append(text[j]);

if len(a)%2==0:
    for k in range(0,(len(a)/2)):
        a[k], a[len(a)-1-k] = a[len(a)-1-k], a[k];
    return ''.join(a);
else:
    for k in range(0,(len(a)-1)/2):
        a[k], a[len(a)-1-k] = a[len(a)-1-k], a[k];
    return ''.join(a);

Sorry it seems a bit messy to yours. But I didn't know about the extra arguments of range(). I'm guessing yours means it starts at the last index and goes back one by one?

Thanks.


#3

@textrunner53160

There are a few solutions that appear to be the most consce.

Here is a recursion one.

Python: Recursive reverse

def reverse(text, nt=''):
    return nt if not text else reverse(text[1:], text[0] + nt)

Here is one using a generator

Python: Generator reverse

def reverse(text):
    return ''.join(letter for letter in (text[(index + 1) * -1] for index, char in enumerate(text)))

Here a final one, that cheats by using the indexing

Python: Generator indexing reverse

def reverse(text):
    return ''.join(letter for letter in list(text)[::-1])

See there are a bunch of different ways to go about it.

How ever you like to program will work. Just remember to complete the task in the simplest way you know how, and do not worry about how others will thing of it.


#4

def reverse(text):
newstring=""
for digit in range(len(text)-1,-1,-1):
newstring=newstring+text[digit]
return newstring