2017-10-14 3 views
1

を持っている場合でも、私は、文字列が回文であるかどうかをテストする機能を持って、Noneを返します:機能は、私はリターンコマンド

def palindrome(raw_text): 
    # first to convert raw_text to a string of lower case letters and remove the space 
    text = raw_text.lower() 
    text = text.replace(' ', '') 

    print('text is now', text) 
    print('length of text is', len(text)) 
    if len(text) == 1 or len(text) == 0: 
     return True 
    else: 
     if text[0] == text[-1]: 
      print('so far so good') 
      palindrome(text[1:-1]) 
     else: 
      return False 

デバッグのためにそれを明確にするためには、私は私を助けるために、いくつかの印刷コマンドを追加しました。 私がしようとした場合:

raw_text = 'abcba' 
print(palindrome(raw_text)) 

私が取得します:

text is now abcba 
length of text is 5 
so far so good 
text is now bcb 
length of text is 3 
so far so good 
text is now c 
length of text is 1 
None 

をなぜ私が最後になし得ていないのですか?私はちょうどraw_text = 'a'を与えるとlen(text) == 1 or 0

ためreturn Trueコマンドを持っていた、それは私を与える:

text is now a 
length of text is 1 
True 
+0

私はこれを再帰について学ぶ練習でない限り、簡単に再帰なしで行うことができます。 –

+1

@ PM2Ringこれは実際に再帰を実行することです。それ以外の場合は、[:: - 1]を使用して比較します。 THanks –

答えて

3

あなたが適切に再帰を忘れていました。

return palindrome(text[1:-1]) 
+0

GOt it !!!ありがとう!!!これは再帰の詳細です。そのキーワードを質問に追加する必要があります –

0

@Ignacio Vazquez-Abramsが述べたように、私は正しく再発しませんでした。 実際には、このコードを複雑にする必要はありません。 私は次のように改訂しました:

def palindrome(raw_text): 
    # first to convert raw_text to a string of lower case letters and remove the space 
    text = raw_text.lower() 
    text = text.replace(' ', '') 

    print('text is now', text) 
    print('length of text is', len(text)) 

    if len(text) <= 3: 
     return text[0] == text[-1] 
    else: 
     return text[0] == text[-1] and palindrome(text[1:-1]) 
関連する問題