7. Reverse


#1



Hi everybody! I run this code in Python 3.4 and it worked perfectly, however in the Codecademy interface i got this error.

Thanks in advance


File "python", line 5
return "".join(newtext)
^
SyntaxError: invalid syntax


def reverse(text):
    newtext = [ ]
    for l in range(len(text)-1, -1, -1):
        newtext.append(text[l]
    return "".join(newtext)

x = raw_input('Which word do you wanna reverse?')

print reverse(x)


#2

look on this line:

newtext.append(text[l]

the parentheses don't match


#3

Hey there, could you explain to me what does this line do?

"for l in range(len(text)-1, -1, -1):"

I didn't catch that :frowning:

Like, what does these 3 'blocks' means?
[len(text)-1] → [-1] → [-1].

Thanks.

Oops. Already saw other post with the explanation i wanted, sorry...


#4

range() can have 3 arguments:

range(start, stop, step)

so len(text)-1 is the start value. -1 is the stop value. and -1 is the step, so we go in reverse. (the step should be pretty obvious)

well, if we have the following string: "hello", the length is 5 but the indexes are: 0, 1,2,3,4. since indexes are zero indexed based. that is why you do len - 1, otherwise you get an index error.

range does not include the stop value, so if you would have 0 as stop value, the h of hello wouldn't be added to the reverse string

but you should really write your own solution, that teaches you so much more


#5

"but you should really write your own solution, that teaches you so much more"

What can I do if I can't think of anyways to solve this problem myself? Am I supposed to right now? Did I miss something?

I've sat here thinking a while and these problems given have given me some trouble while others haven't. I feel like I'm not able to grasp what I learn and use it for myself.


#6

You can see how far you can get, if you really stuck, you can make a new forum topic and we can help you in the right direction. He now just asked me to explain someone else solution.

if he would have included his own code, i can help him better.

right there is the difference between writing code and programming. Yes, this challenge are tricky, but they can stimulate your programming to the next level.

Some general tips:

add a function call, then inside the function add print statements so you can see what your function is doing, this helps a lot


#7

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