7. Reversed. Not where to from here


#1



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


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


This is obviously some kind of glitch. Can anyone help me solve this issue?


def reverse(text):
    result = ' '
    for i in text:
        result = i + result
    return result


#2

you initially set result to ' '

that means your actual result is
'!nohtyP '
^ note the empty space.

That's what this looks like from my angle.

so result = ''


#3

Oh silly me! Did not spot that at all. Removing the space solved the issue.

Thank you so much for your time.


#4

def reverse(text):
rev = ' '
length = len(text)
for index in range(len):
rev = rev + text[len - (index + 1)] #index starts from 0
return rev

--Kumar


#5

what does setting something equal to "" do? i must have forgotten or something


#6

We do it to store in an empty string. In my code above, the variable 'get filled' in the loop. Sorry I'm not the best at explaining things.


#7

Is there a reason that i'm missing for why does the line ''result = i + result'' reads backwards while 'result = result + i' would read it normally? Shouldn't the second one remain the same as it is now while the first one just print 'Python! ' with the space at the end?


#8

Noob here. At first glance it does seem that way, I had the same problem. If you test a short word in your head, it makes sense. Let's use pig.
so result is first empty, so the first iteration will put in the "p" into our string.
result = p
the next iteration will take the "i""
result = "i" + "p" = "ip"
next:
result = "g" + "ip" = "gip"

if you changed it to result = "result" + "i" you would get "pig" back instead.

I don't really understand the other solution mentioned here in the forums, but this solution is super elegant and simple. And for whatever reason the setup mixes up the brain so it doesn't seem to come to someone right away.


#9

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