-2

I need to write a function that determines if a given string is a palindrome. Here is what I wrote so far:

def isPalindrome(string):
    found = False
    for i in range(len(string)):
        if string[i] == string[len(string) - 1 - i]:
            found = True

    if found == True:
        print("Inserted string is a palindrome. ")
    else:
        print("Inserted string is not a palindrome. ")

    return

I iterate over the string, and check if forward and backward iteration gives equal characters. But if I apply this program by executing isPalindrome("hello") , it says this is a palindrome. It doesn't give me the correct output. Could someone please point out any mistake I made, so that I may learn from that.

Kamil
  • 227
  • 4
  • 14
  • Check if the letters DON'T match. As soon as this happens, conclude it's not a palindrome. – uselpa Oct 25 '15 at 21:36
  • You're setting found to True if *any* mirror pairs of characters match. Instead, you want True is *all* mirror pairs match. So initialize it to True, then in the loop set it to False if they *don't* match. – Tom Karzes Oct 25 '15 at 21:38

1 Answers1

2

You set found to true the moment you find any character that is equal to the 'mirror' character. For a word with an odd number of characters, that is always going to be true (the middle character is equal to the middle character), for example, but other words are going to generate a false match too. Take the word winner for example, the two ns in there are in mirror positions and your function will proclaim it a palindrome while clearly it is not.

Instead of setting found to true, exit early if you find a mismatch:

found = True
for i in range(len(string)):
    if string[i] != string[len(string) - 1 - i]:
        found = False
        break

So you start out assuming it is a palindrome, and you exit when you find evidence to the contrary.

Note that you could stop checking when you have checked half the string:

for i in range((len(string) + 1) // 2):
    if string[i] != string[len(string) - 1 - i]:
        found = False
        break

or you could just test if the string is equal to its reverse; the [::-1] gives you the string reversed:

string == string[::-1]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343