String revers help please


#1

def reverse(text):
list=[]
for character in text:
list.append(character)
index=-1
message=[]
for j in range(1,len(list)):
for i in list:
if i==list[index]:
index-=1
message.append(list[index])
return "".join(message)

I cant understand what is wrong with this code. IT seems logical to work but doesn't can someone explain me please why this doesn't work? I don't want the solution. Thanks!


#2

Explain to us how your code acts differently from what you want so that we know what we're looking for! This is how you start solving it yourself anyways, right.

Also make sure that your code is intact, it should be possible to run what you posted without modification and get the same behaviour as you are describing.


#3

list index out of range
index= -1
if i==list[index]

index of list starts from zero not from -1 and you decrease this value (index - = 1 )


#4

Ok, I am trying to make a string appear reversed for example Python! --> !nohtyP and also for text too. Thanks!


#5

Hello, I did this because I want to make it equal to the last element of the list and then append it to the list.


#6

So what happens instead?


#7

It returns nohtyp but if I enter a different value for example hello will output olllleh and if i enter a bigger string will output index out of range.


#8

Do you really ever need to compare two characters? If you think about how you would reverse a string manually, you would only ever need to look at one character at a time, never compare two of them.

You can add prints in your function to follow along in what your function does. Make it explain to you what it does step by step, and compare that to what you want it to be doing.

The code you posted is still missing indentation!


#9

Oh but can you explain me please what it does because I am a bit confused.


#10

What what does? It's your code! And I can't even see it due to formatting! @hellboy24045 came up with a pretty convincing suggestion for what was wrong, but couldn't test it because your code can't be executed!


#11

def reverse(text):
list=[]
for character in text:
list.append(character)
index=-1
message=[]
for j in range(1,len(list)):
for i in list:
if i==list[index]:
index-=1
message.append(list[index])
return "".join(message)

I copy paste it from codeacademy


#12

Never mind figure it out.