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


#1



https://www.codeacademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#


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!
~Joseph


#2

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!')

#4

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:
        a.append(text[b-1])
        b -= 1
    return ''.join(a)
print reverse("Python!")

#5

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

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

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


#6

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).


#7

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


#8

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!")

#10

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!


#11

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.


#12

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