7. reverse question


#1

I'm not sure what the issue is with my current code. I know there are more efficient ways to reverse a word but I wanted to figure out how to do it this way, if possible? Thanks!

def reverse(text):
----new_word = []
----if type(text) == str:
--------for letter in text:
------------a = (len(text) - 1) - text.index(letter)
------------new_word.insert(letter, a)
--------return "".join(new_word)
----else:
--------return False

code with format:

def reverse(text):
    new_word = []
    if type(text) == str:
        for letter in text:
            a = (len(text) -  1) -  text.index(letter)
            new_word.insert(letter, a)
        return "".join(new_word)
    else:
        return False

#2

You are using the insert function wrong, the first argument should be the index position (a) and the second argument the thing you want to insert, in your case letter. Then there is another problem, take a look at this code, i know, i tempered with it, but i only corrected the insert function, and added some print statements (oh, and a function call at the end so we can see what is happening):

def reverse(text):
    new_word = []
    if type(text) == str:
        for letter in text:
            print letter
            a = (len(text) -  1) -  text.index(letter)
            print a
            new_word.insert(a,letter)
            print new_word
        return "".join(new_word)
    else:
        return False
reverse("abc")

as you can see (take some time to study the code) b will be inserted at index 1 (second position, since counting starts from zero), which means you are not reversing the list. I have a suggestion, you can simple loop over the list, and insert everything at index 0, does that help?


#4