2017-10-18 54 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