【问题标题】:Implementation of Naive string matching algorithmNaive字符串匹配算法的实现
【发布时间】:2020-06-09 17:33:00
【问题描述】:

我发现了一个非常有用的关于 Naive 字符串算法的代码,它是用 python 编写的,但它似乎没有运行有什么问题?

def naive(p, t):
occurrences = []
for i in range(len(t) - len(p) + 1):  # loop over alignments
    match = True
    for j in range(len(p)):           # loop over characters
        if t[i+j] != p[j]:            # compare characters
            match = False             # mismatch; reject alignment
            break                     #goes back to the outer loop and start the next step of looping in the alignment
    if match:                         #if match remained true 
      occurrences.append(i)           # all chars matched; record
return occurrences

naive("asge","asgefjlso") #to run #但它不运行也不显示任何东西

谁能帮我解释一下 if t[i+j] != p[j] 是什么意思?

【问题讨论】:

  • 你能发布示例输入和预期输出吗
  • "我在 Naive 字符串算法上找到了一个非常有用的代码,它是用 python 编写的,但它似乎没有运行"——如果它没有运行,它在什么意义上有用?这就像说“我找到了一辆非常有用的汽车,但我无法驾驶它。”另外,你的问题不清楚。您是在问!= 在 Python 中的含义吗?如果这是您的问题,您可以从基本教程中受益。
  • 我的问题是关于这部分如果 t[i+j] , i+j 在内部循环中表示什么?

标签: python python-3.x algorithm search


【解决方案1】:

我假设你已经执行了与上面所附格式相同的代码,那么它不会因为缩进问题而运行,正确的代码与正确的缩进如下

def naive(p, t):
    occurrences = []
    for i in range(len(t) - len(p) + 1):  # loop over alignments
        match = True
        for j in range(len(p)):             # loop over characters
            if t[i+j] != p[j]:                # compare characters
                match = False                  # mismatch; reject alignment
                break                          #goes back to the outer loop 
                                               # and start the 
                                          #next 
                                         #step of looping in the alignment
    if match:                             #if match remained true 
        occurrences.append(i)               # all chars matched; record
    return occurrences

【讨论】:

  • @Shehab 你能解释一下你遇到了什么类型的错误吗?
  • 没有任何错误,它编译成功但没有显示结果
  • @Shehab 实际上,当您调用函数时,它会返回出现次数,您必须打印出现次数才能看到输出,使用 print(naive("asge","asgefjlso") )
  • 如果这部分是 t[i+j],i+j 表示什么?
  • @Shehab 看到你比较了字符串 t 和字符串 p 的字符。您正在运行从 0 到 len(p)-1 的 for 循环 (j)。在该循环中,您首先检查 t[i] 是否与 p[j] (j=0) 匹配,即第一个字符,如果匹配,则增加 j 检查 p 的每个连续元素,即 p[j] 是否与 t[i +j]。我们只是在两个字符串中向前推进,检查两者中是否出现相同的字符。如果我们发现不匹配,我们会打破循环
猜你喜欢
  • 2018-04-05
  • 1970-01-01
  • 2012-12-12
  • 2012-07-30
  • 2012-02-23
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
相关资源
最近更新 更多