Skip to content

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.

  1. Can we access the characters in the string from the end to the beginning?
  2. 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.

  1. Can we access the characters in the string from the beginning to the end?
  2. 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.

1
2
3
4
5
6
7
# Assume s is initialized

idx = len(s) - 1     # start from the end
while idx >= 0:      # loop until beginning

  idx = idx - 1      # move to the left
print(rev)           # assume solution in rev
1
2
3
4
5
6
7
# Assume s is initialized
rev = ""             # store the reverse

while ...:           # assume we can loop
  rev = rev + s[idx] # concatenate
                     #   assume we have idx
print(rev)           # print reverse
1
2
3
4
5
6
7
# Assume s is initialized
rev = ""             # store the reverse
idx = len(s) - 1     # start from the end
while idx >= 0:      # loop until beginning
  rev = rev + s[idx] # concatenate
  idx = idx - 1      # move to the left
print(rev)           # print reverse

  1. 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.