Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to efficiently search for a pattern string within another bigger one, in Python?

"""
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
Comment

PREVIOUS NEXT
Code Example
Python :: python to exe online 
Python :: how to create tkinter window 
Python :: python tkinter button color 
Python :: render django views 
Python :: ipython and virtualenvs 
Python :: max and min int in python 
Python :: error handling in python 
Python :: Math Module degrees() Function in python 
Python :: Requested runtime (python-3.7.5) is not available for this stack (heroku-20). 
Python :: python readlines strip 
Python :: python timeit function return value 
Python :: text color python tkinter 
Python :: remove a first array of item in python 
Python :: normalize function 
Python :: python or 
Python :: how to run python in atom 
Python :: df from wikipedia table 
Python :: how to make code to do something for curtain number of seconds python 
Python :: dockerize django app 
Python :: for in list start with index python 
Python :: insta bs2json 
Python :: Get percentage of missing values pyspark all columns 
Python :: pytorch dataloader to device 
Python :: STATPC 
Python :: Python Import all names 
Python :: python match case example 
Python :: Import "sendgrid" could not be resolved django 
Python :: pythonhashseed 
Python :: rsa decryption 
Python :: Python .on event triggers 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =