Reputation: 13
So, i am writing a code to check whether the entered string is a palindrome or not, i have written the following code, but its not working properly, for e.g, if i input "race" it still says TRUE, although it should say FALSE, Please help. This is the code
string = input("Please enter any word: ")
a = 0
string_length = len(string)
for string_index in range(string_length-1, -1, -1):
character = string[string_index]
if string[a] == character:
a = a + 1
b = "TRUE"
else:
b = "FALSE"
print(b)
Upvotes: 1
Views: 115
Reputation: 234
The correct code:
a = 0
string_length = len(string)
for string_index in range(string_length-1, -1, -1):
character = string[string_index]
if string[a] == character:
a = a + 1
b = "TRUE"
else:
b = "FALSE"
break; # this line was missing
print(b)
Upvotes: 2
Reputation:
string = input("Please enter any word: ")
string_length = len(string)
start_index = 0
count = 0
end_index = string_length - 1
for string_index in range(int(string_length/2)):
if string[start_index] == string[end_index]:
start_index = start_index + 1
end_index = end_index - 1
count += 1
else:
pass
print("Palendrome") if count == int(string_length/2) else print("Not Palendrome")
Explanation: To check for palendrome string compare the first and last character upto the comparison comes to middle of string
for string_index in range(int(string_length/2)):
compare the first character and last character:
if string[start_index] == string[end_index]:
Update the start_index and end_index and count:
start_index = start_index + 1
end_index = end_index - 1
count += 1
If count is equal to half the length of string then it is definitely a Palendrome
print("Palendrome") if count == int(string_length/2) else print("Not Palendrome")
Upvotes: 0
Reputation: 51643
In addition to this answer by מתן ל:
You can easily compare your input agains itself when reversed - list comprehension makes this trivial:
Simple 1-word and case-aware test:
word = "SomemoS"
print(word == word[::-1]) # word[::-1] simply reverses the word and prints True if same
Case insensitive and allow punctuation
A palindrom is readable from both sides. Depending on the rules for palindrom-ness you might allow for ignored casing and even eleminate whitespaces and punctuation marks.
lower()
to it word = [c.lower() for c in "No, it can assess an action." if c not in ',. !?']
print(word == word[::-1]) # True as well
Upvotes: 2