Python 3.2回文 [英] Python 3.2 palindrome
问题描述
我正在做一些python在线教程,但我被困在一个练习中:回文词是一个单词,其拼写与反向相同.例如,单词
I'm doing some python online tutorials, and I got stuck at an exercise:A palindrome is a word which is spelled the same forwards as backwards. For example, the word
赛车
是回文:第一个和最后一个字母相同(r),第二个和倒数第二个字母相同(a),依此类推.编写一个函数isPalindrome(S),它以字符串S作为输入,如果字符串是回文,则返回True,否则返回False. 这些是我写的代码:
is a palindrome: the first and last letters are the same (r), the second and second-last letters are the same (a), etc. Write a function isPalindrome(S) which takes a string S as input, and returns True if the string is a palindrome, and False otherwise. These is the code I wrote :
def isPalindrome(S):
if S[0] == S[-1]
return print("True")
elif S[0] == S[-1] and S[1] == S[-2] :
return print("True")
else:
return print("False")
但是,如果单词是例如,, sarcas ,,,则输出不正确.因此,我需要对我的代码进行修复,以使其适用于任何单词.
But, if the word is for example ,,sarcas,, , the output is incorect. So I need a fix to my code so it works for any word.
推荐答案
一种单行解决方案,但是O(n)和内存昂贵:
A one line solution but O(n) and memory expensive is :
def isPalindrome(word) : return word == word[::-1]
使用相同内存量的O(n/2)解决方案是:
A O(n/2) solution that uses the same amount of memory is:
def palindrome(word):
for i in range(len(word)//2):
if word[i] != word[-1-i]:
return False
return True
这是@LennartRegebro提到的把戏
This is the trick @LennartRegebro mentioned
这篇关于Python 3.2回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!