For pogs and gerald_sky I’ll explain my code:
def reverse(text):
# Our empty string for the reversed text
reversed_text = ""
# Note: Indices are starting with zero and the last number in ranges aren't included
for i in range(len(text)):
reversed_text += text[len(text)-1-i]
return reversed_text
Let’s start to invoke the function with a real input:
reverse("cat")
What is happening in that function if the input is “cat”?
First the variable text will be assigned to the String “cat” (text = “cat”).
len(text)
returns the length of the input string, which here is “cat” and therefore has a length of 3.
The condition for the loop cycle is that variable i has to be in range(len(text))
, in our case it’s range(3)
, because like said before the length of the word “cat” is 3.
for i in range(len(text)):
We know that range(3)
generates the list [0,1,2]
. The loop will iterate / cycle over the list [0,1,2] (which is equal to range(3)
) till i takes a value which isn’t in range (here it is i = [] which isn’t in the list [0,1,2], is the empty list):
After the last iteration (where i = 2) the for-loop will be cancelled and the the program flow will continue at the line outside the “for-loop zone” which is return reversed_text once the the given range is being achieved.
But why reversed_text += text[len(text)-1-i]
?
We know that strings can be accessed like lists. The String “cat” can be imagined as ["c","a","t"]
precisely text = ["c","a","t"]
. You can access the elements of a list by naming the index of the element e.g. for the first element like this: text[0]
. But we want to reverse the input word which is “cat” to “tac”.
The idea is to access the last element “t” append it to the empty list called reversed_text
, access the 2nd last element which is “a”, append it to reversed_text
(which has the string “ta”) and at last append the first element “c” (reversed_text = "cat"
; equal to: reversed_text = text[2] + text[1] + text[0]
).
Let’s sum it up:
- We know that the variable i will start with the first element of the range which is 0
- The last element of a text can be accessed like this
text[len(text)-1]
- For text = “cat” we have to do text[len(text)-1-0] + text[len(text)-1-1] + text[len(text)-1-2]
Sorry for the formatting. I’ll polish it later… Hope that I could help you guys a bit…