Reverse


#1



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


When I run the following code, it shows the reverse working correctly for any string I pass to reverse(). However, when I remove the final print command, the error message I get states:

"Oops, try again. Your function fails on reverse("Python!"). It returns "Pyt!nohtyP" when it should return "!nohtyP".

My concept was to build a list with the correct number of letters (if I didn't I was getting an error as the list didn't have anything in it), then replace each one using the index of each item but counting down, not up.


When I run the code (as shown - with the final print command), the result on the console is "987654321"

Any ideas?


rev_list = []

def reverse(text):
    count = 0
    for n in text:

        rev_list.insert(count, str(n))
        count += 1

    
    count = len(rev_list) - 1    
    for x in text:
        if count >= 0:
            print count
            rev_list[count] = str(x)
            count -= 1
            print rev_list
        
    a = ""
    for st in rev_list:
        a = a + st
    
    return a

print reverse("123456789")


#2

If you call the function twice with the same input, should it then produce the same result twice?


#3

How frustrating!

I should have put the rev_list = [ ] within the function (above "for n in text")...

Thanks for your help!


#4

Hi

Here I made a much simpler solution :smiley:

def reverse(x):
    l=len(x)
    reverseWord=""
    for i in range(l):
        reverseWord=reverseWord+x[l-i-1]
    return reverseWord

#5

Hello everybody!
Can anyone please explain to me why the following code does not work?
Thanks!

def reverse (text):
t=[]
for k in text:
t.append(k)

for i in range(0,len(t)):
    for j in range(0,len(t)):
        if i+j==len(t)-1:
            a=t[i]
            t[i]=t[j]
            t[j]=a

reverse_word=''
for i in range(0,len(t)):
    reverse_word=reverse_word+t[i]

return reverse_word

#7

Thank you very much friend!

I just added a "/2" as you suggested and it works!


#8

could you explain this a little bit for me? I'm struggling to get my head around it.

reverseword is equal to reverseword plus the empty string. the empty string is modified by the list, but I am not able to follow the l - i - 1 part.

Are you substracting the values from each other? and why not

reverseword += x[l-i-1]

Thanks


#11

Hi all!)
Here is my short code interpretation, maybe it'll help you:

def reverse(text):
    newt = ""
    t = len(text) - 1
    while t >= 0:
        newt += text[t]
        t -= 1
    return newt

#13

quite simple & easy to understand

def reverse(text):
    rev = ""
    for char in text:
        rev = char + rev
    return rev

#14