2017-10-14 3 views
1

J'ai une fonction pour tester si une chaîne est palindrome ou non:fonction retourne Aucun, même si je dois revenir commande

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 

Pour ce faire clair pour le débogage, j'ai ajouté quelques commandes d'impression pour me aider . si je tente:

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

je vais obtenir:

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 

Alors, pourquoi suis-je recevoir une None à la fin? J'ai eu la commande return True pour len(text) == 1 or 0

Si je viens de donner raw_text = 'a', il me donnera:

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

BTW, vous pouvez le faire facilement sans récursion ... à moins que cela est un exercice dans l'apprentissage de la récursivité. –

+1

@ PM2Ring c'est en effet pour pratiquer la récursivité. Sinon, je vais simplement utiliser [:: - 1] pour comparer. THanks –

Répondre

3

Vous avez oublié de récursivité correctement.

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

Allez-y !!! Merci!!! Donc, c'est plus sur la récursivité. Je dois ajouter ce mot-clé à la question –

0

Merci, comme @Ignacio Vazquez-Abrams mentionné, je n'ai pas recurse correctement. En fait, le code n'a pas besoin d'être aussi compliqué. Je l'ai revu à:

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])