我想知道如何编写一个递归函数(只有一个参数)来返回子字符串“ou”在字符串中出现的次数。我感到困惑的是,除了len之外,我不能使用任何内置的字符串函数,也不能使用字符串运算符[]以及索引和拼接。所以我不能使用find内置的find函数
我记得看过类似这样的东西,但它使用了两个参数,并且还使用了find()方法
def count_it(target, key):
index = target.find(key)
if index >= 0:
return 1 + count_it(target[index+len(key):], key)
else:
return 0发布于 2011-11-02 04:24:49
效率非常低,但应该可以工作:
def count_it(target):
if len(target) < 2:
return 0
else:
return (target[:2] == 'ou') + count_it(target[1:])在线查看它的工作方式:ideone
这基本上与您发布的代码的思想相同,只是它一次只在字符串中移动一个字符,而不是使用find跳转到下一个匹配。
发布于 2011-11-02 04:42:42
试试这个,它适用于一般情况(任何key的值,不仅仅是'ou'):
def count_it(target, key):
if len(target) < len(key):
return 0
found = True
for i in xrange(len(key)):
if target[i] != key[i]:
found = False
break
if found:
return 1 + count_it(target[len(key):], key)
else:
return count_it(target[1:], key)https://stackoverflow.com/questions/7972398
复制相似问题