我有一个程序执行简单的回文检查,比较字符串的每一端,然后递归地执行原始字符串的子字符串。也就是说,我将str [0]与str [-1]进行比较,执行str [1,-1]并重复比较。我在逐步执行代码时发现的是,当我要求函数check_palin()返回1时,它返回None。我可以清楚地看到它执行' return语句,但是当我要求它返回1时它总是返回None。但是,它正确地返回0。返回True / False时会出现相同的行为。这是我的代码。我做错了什么?
def check_palin(s):
global init
print("Init is %d" %(init))
if len(s) <= 1 :
if not init :
print("returning 1")
return True
else :
print("Please supply a string of atleast 2 characters! Exiting...\n")
print("returning 0")
return False
else :
init = 0
if first_word(s) == last_word(s) :
check_palin(middle(s))
else :
print("returning 0")
return False
def first_word(s) :
return s[0]
def last_word(s):
return s[-1]
def middle(s):
return s[1:-1]
init = 1
s = raw_input("Please enter a string")
print(check_palin(s))
if not check_palin(s) :
print ("String %s IS NOT a palindrome!" %(s))
else :
print ("String %s IS a palindrome!" %(s))
Output:
Please enter a stringababa
Init is 1
Init is 0
Init is 0
returning 1
None
Init is 0
Init is 0
Init is 0
returning 1
String ababa IS NOT a palindrome!
Process finished with exit code 0
答案 0 :(得分:5)
您忘记返回递归的结果。
if first_word(s) == last_word(s) :
return check_palin(middle(s))