A palindrome is a string that reads the same forwards and backwards. Examples of palindromes include “lol”, “abba”, “radar”, and “pickle elkcip”. Indicate whether or not it works under all circumstances described in the following docstring: ”’Return True if string s is a palindrome and return False otherwise.”’
def palindrome2(s):
n = len(s)
pal = True
for i in range(n/2):
if s[i] == s[n-i-1]:
pal = True
else:
pal = False
return pal
I don’t get why this function wouldn’t work. To me, it seems as if the function works. Apparently, the booleans are misused but I don’t get how the booleans above are not used properly. Can someone please explain this to me?
The way the body of the loop is coded the values of
palmay change betweenTrueandFalserepeatedly depending on whether a given pair of characters happen to match or not during that particular iteration.Better to check for inequality, set your Boolean variable
paltoFalseand drop out of the loop immediately then.Something like this:
alternatively, without using a Boolean variable: