在递归函数中保持计数

发布于 2024-12-13 16:08:52 字数 354 浏览 5 评论 0原文

我试图弄清楚如何编写一个递归函数(只有一个参数),该函数返回子字符串“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紧拥背影 2024-12-20 16:08:52

效率非常低,但应该可以工作:

def count_it(target):
    if len(target) < 2:
        return 0
    else:
        return (target[:2] == 'ou') + count_it(target[1:])

在线查看它的工作情况: ideone

它与您发布的代码基本上是相同的想法,除了它一次只在字符串中移动一个字符,而不是使用 find 跳转到下一个匹配项。

Very inefficient, but should work:

def count_it(target):
    if len(target) < 2:
        return 0
    else:
        return (target[:2] == 'ou') + count_it(target[1:])

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.

不必了 2024-12-20 16:08:52

试试这个,它适用于一般情况(键的任何值,而不仅仅是“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)

Try this, it works for the general case (any value of key, not only '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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文