Reputation: 3
I am trying to write a program in Python which will detect that the word given by a user is a palindrome or not.
Here is my code - I operate only on strings - my solution is totally different that other which I have seen here or anywhere, thus I would like you - StactOverFlow users ;) - to check its correctness.
I needn't say that I am not a pro, having rather basic knowledge. However, I would be glad if anyone spend their time and give me some feedback.
# a palindrome
string = input('word: ')
if(len(string) % 2 != 0):
left = string.lower()[0:int((len(string)-1)/2)]
right = string.lower()[int((len(string)-1)/2 + 1): ]
if left == right[::-1]:
print('{} is a palindrome'.format(string.lower()))
else:
print('{} is not a palindrome'.format(string))
else:
left = string.lower()[0:int((len(string)/2))]
right = string.lower()[int(len(string)/2):]
if left == right[::-1]:
print('{} is a palindrome'.format(string.lower()))
else:
print('{} is not a palindrome'.format(string.lower()))
Upvotes: 0
Views: 147
Reputation: 6090
Here you get a oneliner that prints out the palindromes:
print ([v for v in palindromes_test if (len(v) % 2 == 0 and v[0:len(v)//2] == v[len(v)//2:][::-1]) or (len(v) % 2 != 0 and v[0:len(v)//2] == v[len(v)//2+1:][::-1])])
Otherwise:
palindromes_test = ['ABCDCBA','EVE','ABCABC']
for elem in palindromes_test:
if len(elem) % 2 == 0 and elem[0:len(elem)//2] == elem[len(elem)//2:][::-1]:
print ("%s palindrome" % elem)
elif len(elem) % 2 != 0 and elem[0:len(elem)//2] == elem[len(elem)//2+1:][::-1]:
print ("%s palindrome" % elem)
else:
print ("%s not palindrome" % elem)
Output:
ABCDCBA palindrome
EVE palindrome
ABCABC not palindrome
Upvotes: 0
Reputation: 4678
To detect a palindrome just check if the reverse string is equal to the original one
palindromes_test = ['ABCDCBA','EVE','ABCABC']
print ([v for v in palindromes_test if (v == (v[::-1]))])
output
['ABCDCBA', 'EVE']
Upvotes: 1