|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我是这样写的:
大致思想是:找到最中间的一个元素,然后从中间开始从两边进行比较
def restring(temp,a,b):
l1 = len(temp)
if temp[a]!=temp[b]:
return False
else:
return True
if a>=0 or b<=l1:
return restring(temp,a-1,b+1)
temp =‘上海自来水来自cd’
l1 = len(temp)
l2 = l1//2
if l1%2:
a = l2-1
b = l2+1
else:
a = l2-1
b = l2
print(restring(temp,a,b))
最后结果返回True,这是为什么,为什么调递归的时候只比较了一次,递归这块应该怎么实现?
def restring(temp,a,b):
l1 = len(temp)
if temp[a]!=temp[b]:
return False
else:
return True 这个地方用else的话,只要有一个相同就已经返回了true就不会有第二轮的循环了。
if a>=0 or b<=l1: 把return true 换到下面这个条件语句中去
return restring(temp,a-1,b+1)
改成
if temp[a] != tem[b]:
return False
else:
if a >0 :
return restring(temp,a-1,b+1)
else:
return True
|
|