Reverse


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#


Oops, try again. Your function fails on reverse("coolstory"). It returns "yroootslc" when it should return "yrotslooc".


Why doesnt this work?


def reverse(x):
    y=[]
    for letter in x:
        y.append(letter)
    z=[]
    while len(y)>=1:
        z.append(y[len(y)-1])
        y.remove(y[len(y)-1])
    return "".join(z)
print reverse("mahi")


#2

remove() doesn't remove based on index, it removes the first match it can find.

run this code:

def reverse(x):
    y=[]
    for letter in x:
        y.append(letter)
    z=[]
    while len(y)>=1:
        print y
        z.append(y[len(y)-1])
        y.remove(y[len(y)-1])
    return "".join(z)
print reverse("coolstory")

focus particular on the output here:

['c', 'o', 'o', 'l', 's', 't', 'o']
['c', 'o', 'l', 's', 't', 'o']

see how a o of cool gets removed? While it should remove the o of story

like i said, remove() finds the first match it can find, not based in index


#3

Oh yeahh! Totally missed that. Thanks :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.