使用Spyder Python 3.6这段代码不执行,说ispal方法没有定义。然而,当我运行它并首先输入一个整数(比如我的字符串输入= 0)时,它将运行并识别该方法。看起来我必须首先通过除了调用方法之外的分支。感谢批评。
s = input('enter a string: ')
s1 = s
s1 = s1.lower()
s1 = s1.replace(',', '')
s1 = s1.replace(' ', '')
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[1:])
答案 0 :(得分:3)
首先,正如TGKL指出的那样,您在定义之前调用ispal
。所以在调用之前定义它,即:
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[1:])
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')
第二个你的回文递归函数是正确的,除非你在里面调用ispal
。您应该执行ispal(s1[1:])
,而不是ispal(s1[1:-1])
,这将删除刚刚测试过的第一个和最后一个字符。
答案 1 :(得分:1)
您必须首先定义您的方法,然后调用它:
s = raw_input('enter a string: ') #use raw_input so the text it takes will give to you directly a string without ""
s1 = s
s1 = s1.lower()
s1 = s1.replace(',', '')
s1 = s1.replace(' ', '')
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[2:]) # here you put ispal(s1[1:]) it doesn't work properly :/
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')