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.
def palindrome():
x = input("Enter your text:")
x1 = x.replace(" ", "")
y = True
for i in range(len(x1)):
if x1[i] != x1[-(i+1)]:
y = False
break
if y == True:
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 iterator 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.