Reverse Iteration Example

In my Python class I was presented with a challenge problem. We were asked to write a function that detects palindromes and ignores white space.

While this could be more efficiently solved, using slices, I took this as a good time to demonstrate reverse iteration. Here is a breakdown of what I used.

1 def palindrome():
2    x = input("Enter your text:")
3    x1 = x.replace(" ", "")
4    y = True
5    for i in range(len(x1)):
6        if x1[i] != x1[-(i+1)]:
7            y = False
8            break
9    if y == True:
10        print(x + ' is a palindrome')

I iterated upon string x1 and compared using the negative index of x1. Because the positive index starts a 0 and the negative index starts at -1 I have to add one to the index before making negative.

In the example racecar both x1[0] and x1[-(0+1)] will be equivalent to ‘r’. The iteration will continue even past ‘e’. Both pointers will continue all the way to the the point where x1[-(6+1)] == x1[6]. At which point the interator will have reached it’s maximum value of ‘6’ and the for loop can terminate.

Considering the structure of this comparison it is best to assume the provided word is a palindrome and abandon the loop if a mismatch is found.

Next
Previous
comments powered by Disqus