Reverse function is working but not accepted


#1

Hello,

I am doing the codecademy tutorial and I got stuck during a lesson where I have to reverse a word. My function works when I test it myself, but when the program checks it by calling reverse("Python!") it returns "cba!nohtyP". That is not the case when I call it the same way. Then it returns correctly "!nohtyp". Can anyone please help me what is the issue with my code?

The message errors are: There are none, just the program does not believe that it is working :smiley:

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


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


reversed_list = []

def reverse(text):
    length = len(text) - 1
    while length >= 0:
        reversed_list.append(text[length])
        length -= 1
    result = ""
    for i in reversed_list:
        result += i
    return result


#2

Put this inside (empty list) the function!


#3

Thank you! That solved my problem! Do you have any explanation why it is an issue to have it outside the function?


#4

if you call the function multiply times, the list will keep leftovers from earlier function calls (when the list is declared outside the function)

the exercise calls the function multiply times to validate your function reverse correctly


#5

reversed_list = [] is a global variable.
When CC interpreter checks it for various inputs,It already used to have previous string value and the overall o/p looks messy.

This one works fine for one input(not on CC interpreter) but when you call function on various parameters ,It will print gibberish(As string is get added to past values)

also check this..


#6

More..
visualization of the code when list is global and we called function one time..

https://goo.gl/9BZxwq (it works fine in this case)

Visualization of code when you call function multiple times and list still global
https://goo.gl/AXd9Zp

(you can check what happens when you make list local,just copy-paste your code there and visualize the whole execution process)


#10

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