我下载的在线麻省理工学院课程要求学生创建一个函数来测试字符串是否为回文。他们提到了len
并且只拿了一小段字符串。据我所知,我没有使用任务,但我的代码似乎有效。
有什么我想念的吗?
def test_word():
question = input("Do you want to see if a word or sentence is a
palindrome? (y/n)")
question = question.lower()
if question == "y":
sample = input("Provide test word or sentence: \n>>>")
sample = sample.lower()
print(is_palindrome(sample))
test_word()
elif question == "n":
print("Goodbye!")
quit()
else:
print("Y for yes or N for no, please.")
test_word()
def is_palindrome(x):
# Use negative 1 step to reverse order
y = x[::-1]
if x == y:
return True
elif x != y:
return False
test_word()
答案 0 :(得分:0)
您的is_palindrome(x)
功能运行良好,但您可以缩短它。
def is_palindrome(x):
return x == x[::-1]
此外,您可以使用替代非常不直观的[:: - 1]语法(Source)。但是,这可能会更慢,特别是当字符串变长时(检查 mata的评论):
def is_palindrome(x):
return x == ''.join(reversed(x))
并且,您的test_word()
方法会一次又一次地(递归地)调用自己。递归不是必需的,实际上这里有点问题。你应该使用循环:
def test_word():
while True:
question = input("Do you want to see if a word or sentence is a palindrome? (y/n)")
question = question.lower()
if question == "y":
sample = input("Provide test word or sentence: \n>>>")
sample = sample.lower()
print(is_palindrome(sample))
elif question == "n":
print("Goodbye!")
break
else:
print("Y for yes or N for no, please.")
我希望,这有帮助。