7.Reverse - I'd like to refine this code



Hello all! I have solved this exercise but I feel like my code is kinda clunky.
I am hoping to get some critics to help me refine it.
I am here to learn and would love to know:
-Is there a more efficient way I could have codded this?
-Is there a totally different way of solving this you may have taken?
-Does what I have follow good practice?

def reverse(text):
    nlist = []
    reverse = ''
    length = len(text)
    for letter in text:
        nlist.insert(0, letter)    
    for num in range(length):
        reverse += nlist[num]
    return reverse
print reverse('Python!')

Thank you in advance for you feedback!


Here is one way it could be simplified:

def reverse(text):
    nlist = []
    #reverse = ''
    #length = len(text)
    for letter in text:
        nlist.insert(0, letter)    
    #for num in range(len(text)):
        #reverse += nlist[num]
    return ''.join(nlist)
print reverse('Python!')


Hey! You could try this code out. This is the easiest code you could write. I have only used one while loop to turn the list reverse and print it.

def reverse(text):
    a = []
    b = len(text)
    while b > 0:
        b -= 1
    return ''.join(a)
print reverse("Python!")


You actually could cut some lines from that if you did this:

def reverse(text):
    a = []
    #b = len(text)
    while len(a) < len(text):
        #b -= 1
    return ''.join(a)
print reverse("Python!")

Your way is probably more practically, but if you're going for line count...


I don't usually recommend using more than 1 loop for these kinds of functions unless it's nested loops (but you don't need those for reverse).


Yeah! Didn't think of removing the extra variable, b.


Technically, if you made "a" into a string it would be even more simple.

def reverse(text):
    a = ''
    while len(a) < len(text):
        a += text[(len(text)-len(a))-1]
    return a
print reverse("Python!")


Excellent! I did not even think to use join, now I feel silly for over-complicating the problem!

Great use of a while loop! I initially thought of a while loop but couldn't think how to stop it!

This is really cool! Could you explain how you called text like a list? Does a str have indices?

Thanks guys for the enlightenment!


Yes, strings have indices and operate very similar to lists in that regard. You can access any part of a list just like you would access an item in a list.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.