【问题标题】:i want to find number of occurrences of substring in string(without using count function) but i am getting wrong results我想查找字符串中子字符串的出现次数(不使用计数函数),但我得到错误的结果
【发布时间】:2021-12-30 14:17:54
【问题描述】:
s="hellohel"
sub="hel"
count=0
for i in s:
    if sub in s:
        present = True
        count+=1
    else:
        present = False

我得到输出:真 8 输出应该是:True 2

print(present,count)

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您的代码当前检查 hellohel 中的每个字符是否 helhellohel 中。就目前而言,hel 总是在 hellohel 中,所以这永远是正确的。这意味着,您的计数实际上将计算 hellohel 中有多少个字符。

    也许你正在寻找的东西类似于

    s = "hellohel"
    sub = "hel"
    count = 0
    present = False
    for i in range(len(s)):
        if (s[i:i+len(sub)] == sub):
            count += 1
            present = True
    print(count, present) # Prints 2 True   
    

    这段代码需要稍微清理一下,并且可以进行一些优化。但是,这应该有助于将您推向正确的方向。

    【讨论】:

    • 优化之一是present = count > 0
    • 计算机科学中有一个专门用于文本搜索的子领域,它甚至有自己的Wikipedia-article。您可以从诸如Boyer-Moore 算法之类的算法中获取一些优化原理,该算法经常在大学中教授。另一个简单的优化包括检查子字符串是否比要搜索的剩余文本长。
    【解决方案2】:

    所以它显示的原因是因为 for 循环“for i in s:”,因为您的字符串有 8 个“hellohel”位置。因此,每当您尝试运行 for 循环时,它都会运行 8 次。

    【讨论】:

    • 我不认为你理解代码。
    • @BeulahAkindele;不过他正确的。
    • @HenrikKlev...哦,他确实是。我猜他的回答措辞很奇怪。
    【解决方案3】:
    s="hellohel" 
    sub="hel"
    count=0
    for i in s: # this line iterates through each character the string "s" (8 times), assigning the current character to i
        if sub in s: # this line is just checking whether "hel" is in "hellohel" once for every character in "hellohel"
            present = True
            count+=1 # that means it will count to 8 every time, because "hel" is always in "hellohel"
        else:
            present = False
    

    总的来说,不是正确的方法。这里有多个不使用 .count() 但使用 re 的答案,或者除了 vanilla python 什么都没有。 Count number of occurrences of a substring in a string

    【讨论】:

    • 我觉得你也应该更正一下。
    • @BeulahAkindele 我本可以从我链接的线程中复制一个示例,但一般来说,这不是在这里完成的事情。
    • 我只是说,您花时间评论代码。他们已经说过他们不想使用count 函数,你应该刚刚写了更正。我赞成你的回答,因为我没有看到它应该被反对......但你的回答在技术上是不完整的。
    • 从技术上讲,我应该只是将帖子标记为重复,因为通过谷歌搜索可以快速找到多个问题,这些问题具有多个不使用计数功能的答案。接受的答案甚至是从其中一个答案中复制粘贴的。我想我至少会解释为什么他们的所作所为不起作用,而不是无益地标记他们的帖子。我会说我的回答的措辞可能引起了一些混乱,因为我似乎在链接到另一个问题因为它使用了计数。
    猜你喜欢
    • 2023-03-13
    • 2020-02-21
    • 2012-02-12
    • 1970-01-01
    • 2015-01-28
    • 2019-07-09
    • 1970-01-01
    相关资源
    最近更新 更多