I’ve spent a while coding and looking up solutions to the reverse text practice problem. I’m trying to step through logically how the given solution works.
#given solution: def reverse(text): word = "" l = len(text) - 1 while l >= 0: word = word + text[l] #trying to grasp how exactly is this working... l -= 1 return word
My written interpretation of the function, step by step:
- Function creates an empty string in the variable ‘word’
- l is the length of the input “text”, minus 1.
- Creates a while loop for l greater than or equal to 0.
- While Loop Action #1 - iterates through each letter of ‘text’, adding it to the empty string ‘word’.
- While Look Action #2 - subtracts a count from l
- Returns the variable ‘word’
So say for example the input is “Python”. Here’s how I interpret the function to work on the word.
- creates an empty string in ‘word’
- gets the length of “Python” minus 1, which is 5
- Activates the while loop since l is 5, which is greater than or equal to 0.
- Concatenates each letter of the “text” to the empty string, and then subtracts 1 from l:
word = P (l is 5)
word = Py (l is 4)
word = Pyt (l is 3)
word = Pyth ( l is 2)
word = Pytho (l is 1)
word = Python (l is 0)
- Word is returned. Word = Python
Clearly my interpretation is wrong because this function is supposed to be reversing the word. But what am I not considering here? I appreciate any help.