7/15 Interesting solution for reversing a string


#1

I wrote an unconventional way of reversing a string.

The problem with this "solution" is that the website says that it doesn't work. When I run the code, I get:

 Oops, try again. Your function fails on reverse("Python!"). It returns 
 "None" when it should return   "!nohtyP".

The interpreter, however, correctly displays:

 !nohtyP
 None

I realize there must be a much simpler way of doing this, I just haven't looked it up yet. I'm curious why it's coming out wrong and what everyone thinks. I might be missing something obvious.

Here's the code:

def reverse(text):

#I make two lists to store the letters from the text.
letters=[]
reversed_letters=[]

#This stores each letter in the first list. 
for i in text:
    letters.append(i)

#This variable will be used to move back one more letter
#each time the loop runs.
inc = 0

#I move backwards through the first list and store each
#letter in the second list.
for letter in letters:
    reversed_letters.append(letters[(len(letters)-1)-inc])
    inc += 1
    
#This compresses the letters.
print "".join(reversed_letters)


reverse("Python!")

I appreciate any feedback :smile: this is my first language and my first post.


#2

Hallo gumba1033,

Your code is mostly right.
The Problem was just that the function should RETURN something.
Your function is just printing the solution, but if you change the print into a return and then print the solution of the reverse() You will be able to pass this Point.

Here is your modified code :wink:


def reverse(text):

    #I make two lists to store the letters from the text.
    letters = []
    reversed_letters = []

    #This stores each letter in the first list. 
    for i in text:
        letters.append(i)

    #This variable will be used to move back one more letter
    #each time the loop runs.
    inc = 0

        #I move backwards through the first list and store each
        #letter in the second list.
    for letter in letters:
        reversed_letters.append(letters[(len(letters)-1)-inc])
        inc += 1
        #This compresses the letters.
        return "".join(reversed_letters) 

print reverse("Python!")

This is the important line:

return "".join(reversed_letters)


#3

Yup, that worked. Thanks a bunch :grinning: