Loops on Sequence
Learning Objectives
At the end of this sub-unit, students should
- know how to loop on sequence.
Reversing a String
So far, our loop has been on numbers.
What about sequence?
As of now, we have only one sequence which is a string.
Consider the problem of reversing a string.
Given a string s
, print the string in reverse1.
What can we do?
There are several ways to do this. Now, it is often more important to note that it is possible to do it and to attempt it on your own as opposed to always relying on the answer. The answer given in this note is often the one that is easier to write and explain. As always, it is not the only way to do it.
Simply the fact that it is possible to do it a good indicator that it can be a nice exercise even if no answer is given. We will eventually give only either the idea or simply just mentioning that we have a procedure for that. The details should be worked out by the reader.
Now we can discuss the idea that is easy to explain. The problem of reversing a string can be decomposed into two problems below.
- Can we access the characters in the string from the end to the beginning?
- Can we concatenate this character into a variable in the normal order.
Alternative Idea
As usual, there are other solutions. The idea for at least one other solution is to decompose the problem into the following way instead. We will highlight the difference.
- Can we access the characters in the string from the beginning to the end?
- Can we concatenate this character into a variable in the reverse order.
Using this idea, we can try to solve it one by one. When we solve one of the problem, we will leave parts of the code that is supposed to be solved by the other problem as blanks. At the end, we will combine the two solutions.
-
Of course, the more perceptive of you would have realized that this is simply
print(s[::-1])
. But let us imagine that we do not have slicing. ↩