knuth Morris Pratt Algorithm
"""
This implementation demonstrates how 
to efficiently determine if a pattern 
string is a substring of some bigger,
target string.

Example: 
For following input values:
substring = "aefcd"
string = "dcaefcdcdaed"
Output would be: True

Let m be the size of the pattern and 
n be the size of the target string.

Time complexity: O(n+m)
Space complexity: O(m)
"""


def kmp_algorithm(string, substring):
    i, j = 0, 0
    """
    preprocess the pattern string by computing
    a failure function mapping indexes to shifts
    with the aim of reusing previously performed
    comparisons.
    """
    failure = compute_failure_function(substring)
    str_len, substr_len = len(string), len(substring)
    while i < str_len:
        if string[i] == substring[j]:
            # Pattern is found when its last char reached
            if j == substr_len - 1:
                return True
            i += 1
            j += 1
        elif j > 0:
            # Determine next continuation index in pattern
            # by consulting the failure function.
            j = failure[j-1]
        else:
            i += 1
    return False


def compute_failure_function(substring):
    # The failure function maps each index j
    # in pattern P to length of longest prefix
    # of P that is a suffix of P[1:j]
    j, i = 0, 1
    substr_len = len(substring)
    failure = [0] * substr_len
    while i < substr_len:
        if substring[j] == substring[i]:
            # We have matched j + 1 characters
            failure[i] = j + 1
            i += 1
            j += 1
        elif j > 0:
            # Place j just after a prefix that matches
            j = failure[j-1]
        else:
            i += 1
    return failure


print(kmp_algorithm("dcaefcdcdaed", "aefcd"))  # True
print(kmp_algorithm("dcaefccdaed", "aefcd"))  # False
kmp c++
void computeLPSArray(char* pat, int M, int* lps)
{
    int len = 0;
    lps[0] = 0;
    int i = 1;
    while (i < M) {
        if (pat[i] == pat[len]) {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {
            if (len != 0) {
                len = lps[len - 1];
            }
            else
            {
                lps[i] = 0;
                i++;
            }
        }
    }
}
int matchFound=0;
void KMPSearch(char* pat, char* txt)
{
    matchFound=0;
    int M = strlen(pat);
    int N = strlen(txt);
    int lps[M];
    computeLPSArray(pat, M, lps);
    int i = 0;
    int j = 0;
    while (i < N) {
        if (pat[j] == txt[i]) {
            j++;
            i++;
        }
        if (j == M) {
            matchFound++;
//            printf("Found pattern at index %d ", i - j);
            j = lps[j - 1];
        }
        else if (i < N && pat[j] != txt[i]) {
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
}

Python相关代码片段

python env and jupyter kernel

how to remove nested list python

draw.textsize

sec_api python

how to split by multiple things in python

gemini chat bot

pandas max column width

geopandas save as geojson

signals in dajngo

Algorithm Steps for Python Recursion

open file form gui python

ask number gui python

simple windows form python

color selector python

combobox widget in python

Failed to initialize Python.Runtime.dll

loop counter flask

python heartbeat

discord.py remove slash command

Get remainder after division

Sort a list in-place

Remove all elements from a list

os.path.join() function

Arborescence Django

python django projects with source code

check for file python

NameError: name 'scipy' is not defined

django model to dict

add attribute to elementtree

Lambda function to add two numbers

Check if one set is a superset of another

fractions.Fraction class in Python

Invoke a function with its name as a string

Check if a class is a subclass of another class

How to use partial functions

os.path.splitext() function.

Use globals() function to modify a global variable

AttributeError exception

Create a set from a list

Select a random item from a list

program to add two numbers in Python.

get the absolute value of a number in Python

itertools.islice() function in python

Capitalize all words in Python string

max() function in Python

vars() function in Python

setattr() function in Python

get a random integer in a given range in Python

using random.random() function in python

Choose a random item from a list

random.shuffle() function in python

random.choices() function in Python

random.sample() in Python

math.isclose() function in Python

math.comb() in Python

time.localtime() in Python

math.log() in Python

sort array python

get class string py

Binary to Decimal Converter

logging.py

vscode change python version

flask datetime

dbscan clustering implementation python

serving media files in development django

discord bot and flask

histogram of an image in python

numpy get along axis

content delivery network

invalid escape sequence regex python

gnome desktop python

build android app in kivy

python oserror: [errno 24] too many open files

length of array in python

dict.update() with key-value pairs

dict.update() with keyword arguments.

Remove and return a random item from a dictionary

Remove all elements from a dictionary

dict.fromkeys() method in Python

torch set manual seed