Reverse best solution?



Is this actually the simplest code yet?

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


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

def reverse(text):
for j in range(0,len(text)):

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);
    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?




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.


def reverse(text):
for digit in range(len(text)-1,-1,-1):
return newstring