python写算法太慢_作业:在python中实现Z算法,它真的很慢,比简单的字符串搜索慢...

import sys

import time

# z algorithm a.k.a. the fundemental preprocessing algorithm

def z(P, start=1, max_box_size=sys.maxsize):

n = len(P)

boxes = [0] * n

l = -1

r = -1

for k in range(start, n):

if k > r:

i = 0

while k + i < n and P[i] == P[k + i] and i < max_box_size:

i += 1

boxes[k] = i

if i:

l = k

r = k + i - 1

else:

kp = k - l

Z_kp = boxes[kp]

if Z_kp < r - k + 1:

boxes[k] = Z_kp

else:

i = r + 1

while i < n and P[i] == P[i - k] and i - k < max_box_size:

i += 1

boxes[k] = i - k

l = k

r = i - 1

return boxes

# a simple string search

def naive_string_search(P, T):

m = len(T)

n = len(P)

indices = []

for i in range(m - n + 1):

if P == T[i: i + n]:

indices.append(i)

return indices

# string search using the z algorithm.

# The pattern you're searching for is simply prepended to the target text

# and than the z algorithm is run on that concatenation

def z_string_search(P, T):

PT = P + T

n = len(P)

boxes = z(PT, start=n, max_box_size=n)

return list(map(lambda x: x[0]-n, filter(lambda x: x[1] >= n, enumerate(boxes))))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值