Reverse


#1



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


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


The code works perfectly fine for any string (this can be verified by looking at what is printed in the console). The error message does not match up with what the reverse() function actually prints in my console.

I assume it's an error in the way that codecademy is reading and trying to assess the program, rather than the program itself.


word_list = []
new_list = []
def reverse(word):
    for i in word:
        word_list.append(i)
    for j in range((len(word)-1),-1,-1):
        new_list.append(word_list[j])
    return "".join(new_list)
        
print reverse("Python!")


#2

Update**

It's problem of variable scope as mentioned by @rcodeman


Reverse function is working but not accepted
#3

your word_list and new_list should be inside the function.It makes the list empty again.

to understand this call the function twice

print reverse("Python!")
print reverse("anything!")


#4

good point!
As this code works fine for single input (single call),but it need to reset the word_list and new_list again to work on another i/p. (tho re-setting is not solution as error remains ) so creating these empty lists inside the function (locally )is a way!


#5

I tried a eaier way!!

def reverse(text):
new=''
for n in text:
new=n+new
return new


#6

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