回文句或单词
Palindrome Sentence or word
Tom is asked to code the logic to find if a given sentence or a word
is a palindrome or not. Help him to code this logic in Python.
Remember to do a case insensitive check. Refer the sample input and
output statements for more clarifications.
Sample Input 1: Enter the word : Madam
Sample Output 1: Yes, the string is a palindrome !
Sample Input 2: Enter the word : Python
Sample Output 2: No, the string is not a palindrome !
Sample Input 3: Enter the word : Was it a rat I saw
Sample Output 3: Yes, the string is a palindrome !
我编码如下:
t1 = input('Enter the word : ').lower()
if( t1==t1[::-1])
print('Yes, the string is a palindrome !')
else:
print('No, the string is not a palindrome !')
我仍然无法通过所有测试用例。任何人都可以帮我弄清楚吗?
您应该忽略不是字母的字符(如空格),因此您可以filter them out然后进行检查:
t1 = input("Enter the word: ").lower()
# filter out non-letters
t1 = "".join(x for x in t1 if x.isalpha())
if t1 == t1[::-1]:
print("It is a palindrome")
else:
print("It is not a palindrome")
第三个测试用例表明检查中不应考虑空格。因此,请通过以下任一方式忽略它们:
t1 = input().lower().replace(' ', '')
或
t1 = ''.join(input().lower().split())
我真的不会使用简单的“翻转”来比较回文,使用循环仍然是理想的,因为它避免了必须操纵整个字符串:
def isPalindrome(word):
word = word.lower().replace(" ", "")
start, end = 0, len(word)-1
while start < end and word[start] == word[end]:
start += 1
end -= 1
return start >= end
Tom is asked to code the logic to find if a given sentence or a word is a palindrome or not. Help him to code this logic in Python. Remember to do a case insensitive check. Refer the sample input and output statements for more clarifications.
Sample Input 1: Enter the word : Madam
Sample Output 1: Yes, the string is a palindrome !
Sample Input 2: Enter the word : Python
Sample Output 2: No, the string is not a palindrome !
Sample Input 3: Enter the word : Was it a rat I saw
Sample Output 3: Yes, the string is a palindrome !
我编码如下:
t1 = input('Enter the word : ').lower()
if( t1==t1[::-1])
print('Yes, the string is a palindrome !')
else:
print('No, the string is not a palindrome !')
我仍然无法通过所有测试用例。任何人都可以帮我弄清楚吗?
您应该忽略不是字母的字符(如空格),因此您可以filter them out然后进行检查:
t1 = input("Enter the word: ").lower()
# filter out non-letters
t1 = "".join(x for x in t1 if x.isalpha())
if t1 == t1[::-1]:
print("It is a palindrome")
else:
print("It is not a palindrome")
第三个测试用例表明检查中不应考虑空格。因此,请通过以下任一方式忽略它们:
t1 = input().lower().replace(' ', '')
或
t1 = ''.join(input().lower().split())
我真的不会使用简单的“翻转”来比较回文,使用循环仍然是理想的,因为它避免了必须操纵整个字符串:
def isPalindrome(word):
word = word.lower().replace(" ", "")
start, end = 0, len(word)-1
while start < end and word[start] == word[end]:
start += 1
end -= 1
return start >= end