Reverse text - code not working, can anyone take a look?


#1

Hi,

my code for reverse text is not working, does anyone have an idea why?

thanks!

def reverse(text):
text=str(text)
letters=[]
n=len(text)
for i in range(len(text)):
letters[i]=text[n]
n=n-1
return letters


#2

The issue with this code is:

Here you set letters equal to an empty list. All good.

Now you set n equal to the length of the input word, which is greater than 0 (as long as you fill in a word).

But here you are trying to replace the part of the list, on place i, with the last letter of the actual word. The issue about this is, that you don't have anything in the list to replace... :frowning:

Try it this way instead:

def reverse(text):
    text=str(text)
    letters=[]
    n=len(text)
    for i in range(len(text)):
        letters.append(text[i]) #Here you append the list with the letter from you input text
        print letters[::-1] #And here you print out the letters, but backwards [(start of word), (end of word), (steps)], if you leave them, they will be automatically 0 (start of word) and len(word), the actual end of the word
    return letters

#3

Another way to do it is:

def reverse(text):
    text=str(text)
    letters=[]
    n=len(text)
    for i in range(len(text)):
        letters.append(text[i])
        print "letters:", letters
    for x in range(n-1,-1,-1):
        print letters[x],
    return letters

#4

I don't really think this would actually work.
This would be the same result as calling the function list(), where you'll turn something into a list.
Also, you're not supposed to use reversed nor [::-1].

But the idea you gave is good.
After having the string in our list, we can use a loop to get each element and store into a string, which is what I believe we're supposed to return.

variablePosition = len(letters) - 1
for auxVar in range(len(letters)): #Just to loop through
    newString = newString + letters[variablePosition] #At the first execution, you'll get the last element of it
   #Just need to decrement it now.

#5

I haven't thought that part through, to be honest

But it actually worked on IDLE when i tested it :((

Sorry about that part, I haven't read the instructions and just wanted to help out with his code.


#6

I'm not arguing/scolding/calling your attention or anything like that, hope you didn't get that wrong.
I know you wanted to help and you did, seriously.

And you were supposed to return the string reversed, not only the list reversed but I'm pretty sure that the OP will check those hints and find his/her way through it!

Good job though!


#7

It's all right, I'm glad that you pointed it out, or else he would learn it the wrong way ^^

And thanks mate, you did a good job too :smiley: