在递归函数中保持计数
我试图弄清楚如何编写一个递归函数(只有一个参数),该函数返回子字符串“ou”在字符串中出现的次数。我感到困惑的是,除了 len 或字符串运算符 [] 和 [:] 之外,我不允许使用任何内置字符串函数来进行索引和拼接。所以我无法使用 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
I'm trying to figure out how to write a recursive function (with only one parameter) that returns the number of times the substring “ou” appears in the string. Where I'm confused at is that I'm not allowed to use any built-in string functions other than len, or the string operators [] and [:] for indexing and splicing. So I can't use the find built-in find function
I remember seeing something like this, but it uses two parameters and it also uses the find() method
def count_it(target, key):
index = target.find(key)
if index >= 0:
return 1 + count_it(target[index+len(key):], key)
else:
return 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
效率非常低,但应该可以工作:
在线查看它的工作情况: ideone
它与您发布的代码基本上是相同的想法,除了它一次只在字符串中移动一个字符,而不是使用
find
跳转到下一个匹配项。Very inefficient, but should work:
See it working online: ideone
It's basically the same idea as the code you posted, except that it moves only one character at a time through the string instead of using
find
to jump ahead to the next match.试试这个,它适用于一般情况(键的任何值,而不仅仅是“ou”):
Try this, it works for the general case (any value of key, not only 'ou'):