7. Reverse: what is wrong with this code?


#1



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?


letters_list=[]

def reverse(text):
    for n in range(0,len(text)):
        letters_list.append(text[(len(text)-1)-n])
    return ''.join(letters_list)


#2

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

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

The output should be:

eno
owt
eerht

#3

It prints out:

eno
enoowt
enoowteerht

What does this mean?


#4

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.


#5

Okay now I got it! Thanks!


#6

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


#7

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.


#8

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