7. reverse: Why doesn't this work?


#1
def reverse(text):
    rev = []
    while len(text)>0:
        i = text[len(text)]
        rev.append(i)
        text = text[len(text)-1]
        break
    return rev

#2

I think it should be this:

def reverse(text):
    rev = []
    
    while len(text)>0:
        i = text[len(text) - 1] # last character is at this index
        rev.append(i)
        text = text[0 : len(text)-1] # take a substring here, excluding the last character
        # no need of break here        

    return rev
    
print reverse([1, 2, 3, 4]) # test gives -> [4, 3, 2, 1]

P.S. Please format your post as I have done (select entire code block; press Ctrl+Shift+C) from next time. Thanks! :smile:


#3

Thank you very much! I will be sure to format my post, I have actually tried to do it but I didn't know how. Thank you very much again!!!


#4

Does it work for you? If I use your code codeacademy doesn't let me move on

def reverse(text):
        rev = []
        while len(text)>0:
            i = text[len(text)-1]
            rev.append(i)
            text = text[0:len(text)-1]
        print "".join(rev)
        return rev

Plese see results on screen


Any idea?


#5

As the error message says, you are returning a list while it expects the list to be a string. You are printing the string correctly. You just have to return it. Alternatively, you don't even need to use lists in case you are dealing with strings:

def reverse(text):
    rev = "" # string initially
    length = len(text) # avoid having to call `len` method repetitively

    while length > 0:
        i = text[length - 1] # last character is at this index
        rev += i # concatenate the i-th character
        text = text[0 : length - 1] # take a substring here, excluding the last character
        length = length - 1 # decrement length

    return rev
    
print reverse("1234") # test gives -> "4321"

#6

Oh, thanks a lot! I got it. Simply I was confused by result in console


#7