天真字符串匹配算法的实现

问题描述 投票:0回答:1

我在朴素的字符串算法上找到了一个非常有用的代码,该代码是用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")#运行#,但它不运行并且不显示任何内容

[有人也可以请我解释一下,如果t [i + j]!= p [j]意味着做什么吗?

python python-3.x algorithm search
1个回答
0
投票

我假设您已按照与上述相同的格式执行代码,由于缩进问题它将无法运行,带有正确缩进的正确代码如下

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
© www.soinside.com 2019 - 2024. All rights reserved.