15/7 Reverse Unnecessary code?


#1

Hi,

I managed to figure out how to complete this exercise but I can't find a way to make it shorter or more compact than what I've pasted below, mostly referring to the loops.

seems like its possible to index a string and go backwards but the only way that I can think of moving up or down an index is with range(x,x,x). I can't wrap my head around having it in the same line/statement, maybe I'm overthinking it.

Can anyone point me in the right direction?

def reverse(text):
    txt_1 = []
    txt_2 = []
    l = len(text) - 1
    print l
    for char in text:
        txt_1.append(char)
        print txt_1
    for i in range(l,-1,-1):
        txt_2.append(txt_1[i])
        print txt_2
    print "".join(txt_2)
    return "".join(txt_2)
        

reverse("abcd")

#2

5 posts were split to a new topic: Reverse using periodic and other methods


#3

That is what the above code would indicate.

Are you familiar with the built in list() function? This will take a string and convert it to a list. However, do we really need a list to iterate? Answer: no. A string is an iterable, already. No need to convert. Just iterate.

Take this in mind and see if you can simplify your above code. We'll be on hand when you are ready to check it, again.


#4

Thanks for the reply's,

I think i know where I went wrong, had it stuck in my head that '+=' and other operators were only usable with integers. So if you wanted to add something to a string, you'd have to use lists for the '.append(item)' option and then convert back it to a string

Removed the lists, placed a string, used the the second 'for' loop from the previous code, left out the ' l ' variable to free up another line, removed the first 'for' loop and returned the r_txt since there is no need for ' "".join(item) '.
I kept the 'print ....' statement to see the progression of r_txt.

thanks for helping out!

def reverse(txt):
    r_txt = ""
    for i in range((len(txt)-1),-1,-1):
        r_txt += txt[i]
        print r_txt
    return r_txt

#5

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