作业是编写一个递归函数 lenRecur(s) 返回字符串 s 的长度。允许切片,显然 len() 函数不允许。在与下面的代码纠缠了太久之后,我恍然大悟:这实际上就是众所周知的“一行代码”,如此简单!以下是不是“正确”答案,但我仍然想知道为什么它不起作用。我试图递归地分解字符串并用索引计算步数,但索引每次都重置为 0,所以我想创建一个内部函数 countRecur(s,i),它需要 s 和一个初始索引作为参数,并在每次递归时增加索引。最终索引将返回给外部函数。底线:索引正确启动,但 return i 返回 None。
def lenRecur(s):
i=0
def countRecur(s,i):
if s == "":
print "final i = ", i
return i
else:
i+=1
print s
s = countRecur(s[:-1],i)
p = countRecur(s,i)
return p
s = "abc"
q = lenRecur(s)
print q
这是输出:
abc
ab
a
final i = 3
None
请您参考如下方法:
您的问题是您没有返回 s,您应该将其更改为 i,因为它是 s 是字符串时的计数起初。当您不返回它时,您实际上丢弃了 s 并且永远不会设置 p。
def lenRecur(s):
i=0
def countRecur(s,i):
if s == "":
print "final i = ", i
return i
else:
i+=1
print s
i = countRecur(s[:-1],i)
return i
p = countRecur(s,i)
return p
s = "abc"
q = lenRecur(s)
print q
abc
ab
a
final i = 3
3
