7. Reverse: what is wrong with this code?


For some strange reason my code results in the following error message:

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

Where are those extra c, b, and a coming from? I have tried to resubmit and alter the code a bit and closed the page and refreshed it but the extra letters are still there. Am I missing something obvious?


def reverse(text):
    for n in range(0,len(text)):
    return ''.join(letters_list)


Add these lines at the bottom and observe what is printed:

print reverse('one')
print reverse('two')
print reverse('three')

The output should be:



It prints out:


What does this mean?


You mentioned not seeing where cba was coming from.
There's no cba now. There are other characters. What are the extra characters, see those anywhere else, see now where they come from? What's the pattern that is being printed out? What happens if you add more prints with calls to reverse (four, five, six, ..) - what is it doing? That pattern says everything about what your code is doing that it shouldn't be doing.


Okay now I got it! Thanks!


I had the same mistake, I solved it writing the code letters_list=[] inside the function def reverse (text):
Good luck!


To add some background/theory to this:

If possible, it's preferable that functions are entirely self-contained so that nothing other than the arguments affect the return-value of the function.

This is just how like a function of x shouldn't involve the color of the sky:

f(x) = x + is the sky blue?

It also shouldn't fire off nuclear missiles, that would be an unwanted side-effect, there shouldn't be any side-effects if that is not the purpose of the function

Some languages/cultures are more strict about this than others, but it's generally better that functions stay pure whenever possible, it's much easier to reason about code that is written this way.


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