Reputation: 31
I wrote a palindrome iterative method and it returns correct result except for when the string is arena or taxi cat. It returns true for both where it has to return false.
def palIterative(n):
for i in range(0, int(len(n)/2)):
if n[i] != n[len(n) - i - 1]:
return False
break
return True
Upvotes: 3
Views: 1372
Reputation: 42133
Your return True
line exits the loop on the first iteration. So the function will return True for any word that has the same first and last letter. Also, that break statement is unnecessary because the return line above it will exit the whole function before getting to the break
Finally, to be more Pythonic, you should avoid using indexes to go through an array. Try to use iterations on values.
For example:
def isPalindrome(n):
for forward,backward in zip(n,reversed(n)):
if forward != backward:
return False
return True
Note that if you are looking for the shortest way to write the solution, you don't even need loops at all return n == n[::-1]
will do it. It is inherently iterative (as opposed to recursive) because the == comparison will iterate through the list and its reverse to compare elements (you just don't have to tell it how explicitly). You could also see as doing exactly one iteration.
For comparison purposes, a recursive solution would look like this:
def isPalindrome(A):
return not A or A[0]==A[-1] and isPalindrome(A[1:-1])
Upvotes: 0
Reputation: 423
You don't need break
after the return False
statement. Return will break out of a function. The problem though is your return True
statement has one too many tabs. The return True
statement should be after the for loop has completed.
Upvotes: 2
Reputation: 19
def pallindromechecker(a): if a == a[::-1]: print("True") else: print("False")
pallindromechecker("IamaI")
Try the above code. Its an easy way to identify pallindrome
Upvotes: 0