2017-12-26 14 views
0
def ispalindrome(s): 
    """Assumes s is a str 
    returns true if s is a ispalindrome 
    punctuation marks, blanks, and capitals are igored """ 
#s=raw_input("Please enter a word to check if it is a palindrome") 
    def tochars(s): 
    s=s.lower() 
    letters='' 
    for c in s : 
    if c in 'abcdefghijklmnopqrstuvwxyz': 
     letters=letters+c 
    return letters 

    def ispal(s): 
    print ' ispalindrome called with' , s 
    if len(s)<=1 : 
    print "about to return to from base case" 
    return True 
    else : 
     answer = s[0] == s[-1 ] and ispal (s[1:-1]) 
     print "about to return ",answer,"for" ,s 
     return answer 
    return ispal(tochars(s)) 



def testpal(): 
    print 'try doggod' 
    print ispalindrome('doggod') 

나는 위의 코드를 실행할 때 seanlessly 컴파일되지만 아무 것도 반환하지 않습니다. 오류 메시지는 없지만 프로그램이 아무것도 인쇄하지 않습니다. 제발 좀 suggstion주세요.왜 재귀 프로그램을 실행하면 아무 것도 표시되지 않습니다.

+2

을 ...이 경우 * 전체 코드를 * 왜 아무 일이 기대합니까? 당신은 단순히 여러 함수를 정의하지만 그 중 어떤 함수도 호출하지 않습니다 ... –

답변

3

return ispal(tochars(s)) 

가 너무 많이 들여 쓰기 라인입니다.

이렇게하면 ispal(s) 함수의 일부가되므로 결코 호출되지 않습니다.

일반적으로 들여 쓰기가 매우 일치하지 않습니다 (때로는 1 개, 때로는 2 개, 때로는 3 개 공백). 문제를 해결하지 않으면 계속 이와 같은 오류가 발생합니다.

또한, 귀하는 testpal() 기능을 결코 호출하지 않습니다. 이 모든 문제를 해결하는 경우

, 그것은 잘 실행 :

def ispalindrome(s): 
    def tochars(s): 
    s = s.lower() 
    letters = '' 
    for c in s: 
     if c in 'abcdefghijklmnopqrstuvwxyz': 
     letters = letters + c 
    return letters 

    def ispal(s): 
    print 'ispalindrome called with', s 

    if len(s) <= 1: 
     print "about to return to from base case" 
     return True 
    else: 
     answer = s[0] == s[-1 ] and ispal (s[1:-1]) 
     print "about to return ", answer, "for", s 
     return answer 

    return ispal(tochars(s)) 

def testpal(): 
    print 'try doggod' 
    print ispalindrome('doggod') 

testpal()