3

I have the following code, when going through the python, the options aaabaaaa, zzzazzazz gave me the false test.Here is the code, I am not too sure on how to fix it.

def checkPalindrome(inputString):
    n=len(inputString)  
    #if string is one letter
    if n==1:
        return True 
    #if string has more than one letter
    for i in range (0, math.floor(n/2)) :
        if inputString[i]!=inputString[n-1-i]:
            return False
        else:
            return True
M-M
  • 881
  • 2
  • 10
  • 19
  • Error? [tour] = False – gsquaredxc Mar 13 '18 at 00:47
  • 3
    The `else` part needs to be removed, and the `return True` is to go outside the loop. – cs95 Mar 13 '18 at 00:48
  • 1
    Aren't your sample inputs supposed to give false ? *A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar.* – AstroMax Mar 13 '18 at 00:49
  • @AstroMax, Sorry for the misunderstanding, I meant the output was True, which is wrong result. – M-M Mar 13 '18 at 19:27

3 Answers3

2

You have a few issues. The main issue here is that your else clause has a return True inside the loop. What you'd want to do is finish iterating over the string before returning True. If you are familiar with boolean logic, this is the equivalent of short circuiting with AND.

The other issue (not really an issue, more a nitpick) is that you can just use integer division //, instead of having to import math's floor function.

So,

def isPalindrome(string):
    for i in range(0, len(string) // 2):
        if string[i] != string[-(i + 1)]:
            return False

    return True

Another way of handling this would be using all:

def isPalindrome(string):
    return all(x == y for x, y in zip(string, reversed(string)))

Or, taking advantage of python's convenient slice notation for the most concise solution possible, we have:

def isPalindrome(string):
    return string == string[::-1]
cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    although this will still return `False` because the OP's inputs aren't palindromes... :) – Julien Mar 13 '18 at 00:51
  • @Julien Yes, that is my understanding, that they meant the outputs were not "as expected" (false output), haha. Mindreading OP here a bit. – cs95 Mar 13 '18 at 00:52
0

Try this which uses array slicing (reversing an array of chars)

def checkPalindrome(inputString):
    n=len(inputString)  
    #if string is one letter
    if n==1:
        return True 
    #if string has more than one letter
    return inputString==inputString[::-1]
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38
0

Another approach could be using slicing. Strings can be accessed by index like arrays/lists and also be inverted like this.

def isPalindrom(string)
    return string == string[::-1]

the [::-1] slicing returns the reversed string, the comparision with the original string is True if it's the same otherwise false.

Lukr
  • 659
  • 3
  • 14