Reverse


#1


Stuck at Reverse.

My error message is

Your function fails on reverse("Python!"). It returns "!nohtyPcba!nohtyP" when it should return "!nohtyP".

Cannot figure out what's wrong, can you help?

reversed_text = []
def reverse(text):
    i = len(text) - 1
    while i > -1:
        reversed_text.append(text[i])
        i -= 1
    return ''.join(reversed_text)
    
reverse("Python!")

#2

To know what is going on Try to add another test case like

print reverse("someone")

Also add print statements in your function to print out

at each step


#3

I did that, but the results are the same.

New code:

reversed_text = []
def reverse(text):
    i = len(text) - 1
    while i > -1:
        reversed_text.append(text[i])
        print reversed_text
        i -= 1
    return ''.join(reversed_text)
    
print reverse("someone")

New output:

['e']
['e', 'n']
['e', 'n', 'o']
['e', 'n', 'o', 'e']
['e', 'n', 'o', 'e', 'm']
['e', 'n', 'o', 'e', 'm', 'o']
['e', 'n', 'o', 'e', 'm', 'o', 's']
enoemos
None

Same error:

Your function fails on reverse("Python!"). It returns "enoemoscba!nohtyP" when it should return "!nohtyP"


#4

Hi astronautameya,

IIRC the issue you are having stems from having reversed_text declared as a global variable.

A simple fix should be to bring reversed_text inside the function:

def reverse(text):
    reversed_text = []
    i = len(text) - 1
    while i > -1:
        reversed_text.append(text[i])
        i -= 1
    return ''.join(reversed_text)
    
reverse("Python!")

#5

It worked thank you!

Can you help me understand why having it as a global variable was an issue?

AFAIK, calling/ referencing a local variable outside it's loop/ function is an issue, not the other way around.


#6

Calling it a global variable might have been an inaccuracy on my part. My python knowledge is rusty, but I like to think of functions as "black boxes"; they take an input and generate an output. Accessing local variables outside of the function is an issue, accessing global variables within functions might require using the global command.

What's more likely happening is that behind the scenes your function is being called with reverse("abc") and since your reversed_text variable is defined outside of the function it never gets set back to [].

reversed_text = []
def reverse(text):
    i = len(text) - 1
    while i > -1:
        reversed_text.append(text[i])
        print reversed_text
        i -= 1
    return ''.join(reversed_text)
    
reverse("abc")
> cba
reverse("Python!")
> cba!nohtyP
reverse("AddingMore")
> cba!nohtyPeroMgniddA

#7

That makes sense. Thanks a lot :slight_smile:


#8

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