2017-10-18 110 views
1

我下载了一个在线MIT课程,要求学生创建一个函数来测试一个字符串是否是回文。他们提到len并且只取一小段字符串。据我了解,我既不使用任务,但我的代码似乎工作。 有什么我失踪?家庭作业 - 家中自学 - Palindrome

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

如果你的代码正在工作有什么问题? – Rahul

回答

0

is_palindrome(x)功能运作良好,但可以缩短。

def is_palindrome(x): 
    return x == x[::-1] 

另外,还可以使用的替代而直观[:: - 1]语法(Source)。但是,这可能会比较慢,特别是当琴弦长(检查马塔的评论):

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.") 

我希望,这有助于。

+0

谢谢!当我自学时,得到这样的建议是很好的。 – Ruark

+1

不直观是一个tase的问题,我没有找到'''.join(reversed(x))',那么'x [:: - 1]'更好,连接空字符串上的反转对象isn'真的很直观。此外,它可以[方式更慢](https://pastebin.com/jrkdHrDX),特别是当字符串变长时。 'reversed()'的强度是它不必在内存中创建整个反转序列。 – mata

+0

@mata我对此没有足够的了解,我刚刚分享了[源链接](https://stackoverflow.com/a/17331369/6900838)的说法。但是,多亏了你,现在我们知道'x [:: - 1]'快了。 – Alperen