7/15 Reverse


Can someone please explain the precise logic of each part of the solution, step by step


then put at least the solution up here, otherwise i have to navigate to the exercise (given you didn’t share the exercise url), reset, and keep submitting until i get the get code option

What about the solution do you understand? The more i understand what you do and do not understand, the better my answer can be.


Thanks, I added it now.


Honestly the whole thing other than the function Im not understanding, as in the first line.


The short version is that we create an empty string (line 2), in which we are going to store our reversed string.

then we are going to loop over the string (text variable) in reverse using a while loop, appending the characters to word

you could add a function call:

print reverse("hello world")

at the very end of your script, this allows us to insert print statement inside the function we then can actually see:

    while l >= 0: 
        print l, text[l]

this helps to visualize what the program is doing. But we need the function call, otherwise the function won’t execute, and we won’t see the print statements.


can you explain

word = word + text[l]. What does text[l] do?


l -= 1 . why are we subtracting 1 each time from the length of text (which is already subtracted once)


text[l] gets the letters from text using l as index:

x = "hello world"
print x[0]
print x[1]

but instead of fixed numbers like in my example, we use a variable and a loop

the subtraction here:

l = len(text) - 1

is only because strings are zero indexed based, while len() start counting at one. Not subtracting one would cause an IndexError

l -= 1 is what makes everything work, it reduces l so we go from the right hand side of the string to the left hand side of the string, looping in reverse over the string as you like, appending to word so we end up with a reversed string.

if you inserted the print statements like i suggested, this should be visualized? I on purpose choice l (the index) and text[l] (looking up value in string using index), given its the most critical part of the program


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