编写一个递归函数len,该函数接受包含字符串值的参数,并返回字符串中的字符数。 字符串的长度为:
如果字符串为空(“”),则为0
比第一个字符超出字符串长度多1个
这是我到目前为止得到的:
def len(string):
if len(string) == ""
return 0
else:
return string[len(string)+1]
我在做什么错?谢谢
答案 0 :(得分:3)
len()
应该返回一个整数。我认为他们正在寻找这样的东西:
def len(string):
if string == "":
# 0 if the string is empty
return 0
else:
# one more than the length of the string beyond the first character
return 1 + len(string[1:])
答案 1 :(得分:3)
您忘记减少递归调用中的问题。您编写了一个无限递归。关键的声明是重复出现较短的字符串:
return len(string[1:]) + 1