我下载了一门麻省理工学院的在线课程,让它的学生创建一个函数来测试字符串是否是回文。他们提到了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()
发布于 2017-10-18 07:06:54
您的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.")
希望这能帮上忙。
https://stackoverflow.com/questions/46803714
复制相似问题