Reverse function

#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/reverse?action=lesson_resume

<In what way does your code behave incorrectly? Include ALL error messages.>
It does solve half of the challenge, for example abcd becomes dccd.

<What do you expect to happen instead?>
I expect the program to continue solve the remaining part as it did with the first half.

``````def reverse(text):
revers =[]
for char in text:
revers.append(char)
print str(revers) + " This is revers"
for index in range(len(revers)):
revers[index] = revers[len(revers)-(1+index)]
return "".join(revers)
``````

#2

if we add a print statement:

``````def reverse(text):
revers =[]
for char in text:
revers.append(char)
print str(revers) + " This is revers"
for index in range(len(revers)):
print revers
revers[index] = revers[len(revers)-(1+index)]
return "".join(revers)
print reverse("python")
``````

we can see the following output:

``````['p', 'y', 't', 'h', 'o', 'n'] This is revers
['p', 'y', 't', 'h', 'o', 'n'] # good
['n', 'y', 't', 'h', 'o', 'n'] # good
['n', 'o', 't', 'h', 'o', 'n'] # good
['n', 'o', 'h', 'h', 'o', 'n'] # problem
['n', 'o', 'h', 'h', 'o', 'n']
['n', 'o', 'h', 'h', 'o', 'n']
``````

see where i added the problem comment, you overwrote the `t` on index 2, so now it can’t be used for reversing any longer.

Your solution would work, if you would append to a new list.

You now overwrite characters (by updating list) which you still need for successfully reversing the string.

#3

I tried what you advice me to do but I get an error.
Below is the code followed by error:

``````def reverse(text):
revers =[]
final = []
final.append(["O"] * (len(text)+1))
for char in text:
revers.append(char)
for index in range(len(text)):
final[index -1] = revers[len(text)-(1+index)]
return "".join(final)

``````

error message:

Traceback (most recent call last): File “python”, line 10, in
File “python”, line 8, in reverseIndexError: list assignment
index out of range

#4

did you check the value of final? Its a multi-dimensional list, is this what you want?

#5

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