Open In App

Python Program for Rabin-Karp Algorithm for Pattern Searching

Last Updated : 10 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:

Input:  txt[] = "THIS IS A TEST TEXT"
        pat[] = "TEST"
Output: Pattern found at index 10

Input:  txt[] =  "AABAACAADAABAABA"
        pat[] =  "AABA"
Output: Pattern found at index 0
        Pattern found at index 9
        Pattern found at index 12

 

 

The Naive String Matching algorithm slides the pattern one by one. After each slide, one by one checks characters at the current shift, and if all characters match then print the match. Like the Naive Algorithm, the Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, the Rabin Karp algorithm matches the hash value of the pattern with the hash value of the current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp’s algorithm needs to calculate hash values for the following strings.1) Pattern itself.2) All the substrings of the text of length m. 

Python




# Following program is the python implementation of
# Rabin Karp Algorithm given in CLRS book
 
# d is the number of characters in the input alphabet
d = 256
 
# pat  -> pattern
# txt  -> text
# q    -> A prime number
 
def search(pat, txt, q):
    M = len(pat)
    N = len(txt)
    i = 0
    j = 0
    p = 0    # hash value for pattern
    t = 0    # hash value for txt
    h = 1
 
    # The value of h would be "pow(d, M-1)% q"
    for i in xrange(M-1):
        h = (h * d)% q
 
    # Calculate the hash value of pattern and first window
    # of text
    for i in xrange(M):
        p = (d * p + ord(pat[i]))% q
        t = (d * t + ord(txt[i]))% q
 
    # Slide the pattern over text one by one
    for i in xrange(N-M + 1):
        # Check the hash values of current window of text and
        # pattern if the hash values match then only check
        # for characters one by one
        if p == t:
            # Check for characters one by one
            for j in xrange(M):
                if txt[i + j] != pat[j]:
                    break
 
            j+= 1
            # if p == t and pat[0...M-1] = txt[i, i + 1, ...i + M-1]
            if j == M:
                print "Pattern found at index " + str(i)
 
        # Calculate hash value for next window of text: Remove
        # leading digit, add trailing digit
        if i < N-M:
            t = (d*(t-ord(txt[i])*h) + ord(txt[i + M]))% q
 
            # We might get negative values of t, converting it to
            # positive
            if t < 0:
                t = t + q
 
# Driver program to test the above function
txt = "GEEKS FOR GEEKS"
pat = "GEEK"
q = 101 # A prime number
search(pat, txt, q)
 
# This code is contributed by Bhavya Jain


Output:

Pattern found at index 0
Pattern found at index 10

Time Complexity: O(nm), where m is the length of the pattern and n is the length 
Auxiliary Space: O(1).

Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details!



Previous Article
Next Article

Similar Reads

Python Program for KMP Algorithm for Pattern Searching[duplicate]
Python Code # Python program for KMP Algorithm def KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] while i &lt; N: if pat[j] == txt[i]:
2 min read
Python Program for KMP Algorithm for Pattern Searching
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n &gt; m. Examples: Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAABAABA" pat[] = "AABA" Output: Pattern found at ind
2 min read
Python Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14-&gt;21-&gt;11-&gt;30-&gt;10, then function should return false. If key to be searched is 1
4 min read
Python Program to print digit pattern
The program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples: Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *'s that are equivalent to each digit in the integer. Here the first digit is 4 so print four *sin the fir
3 min read
Python 3 | Program to print double sided stair-case pattern
Below mentioned is the Python 3 program to print the double-sided staircase pattern. Examples: Input: 10Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note: This code only works for even values of n. Example1 The given Python code demonstrates a staircase pattern. It d
3 min read
Python Program to print hollow half diamond hash pattern
Give an integer N and the task is to print hollow half diamond pattern. Examples: Input : 6 Output : # # # # # # # # # # # # # # # # # # # # Input : 7 Output : # # # # # # # # # # # # # # # # # # # # # # # # Approach: The idea is to break the pattern into two parts: Upper part: For the upper half start the for loop with iterator (i) from 1 to n and
4 min read
Python program to print the Inverted heart pattern
Let us see how to print an inverted heart pattern in Python. Example: Input: 11 Output: * *** ***** ******* ********* *********** ************* *************** ***************** ******************* ********************* ********* ******** ******* ****** ***** **** Input: 15 Output: * *** ***** ******* ********* *********** ************* ***********
2 min read
Python Program to Print Alphabetic Triangle Pattern
In this article, we examine a recursive method for printing character patterns in Python. Nesting loops are used in the conventional iterative approach to regulating character spacing and printing. We have provided the answer using both methods. This method prints an alphabet pattern in the form of a pyramid. It uses nested loops to print the space
4 min read
Python Program to Print the Natural Numbers Summation Pattern
Given a natural number n, the task is to write a Python program to first find the sum of first n natural numbers and then print each step as a pattern. Input: 5 Output: 1 = 11 + 2 = 31 + 2 + 3 = 61 + 2 + 3 + 4 = 101 + 2 + 3 + 4 + 5 = 15 Input: 10 Output: 1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15 1 + 2 + 3 + 4 + 5 + 6 =
2 min read
Python program to display half diamond pattern of numbers with star border
Given a number n, the task is to write a Python program to print a half-diamond pattern of numbers with a star border. Examples: Input: n = 5 Output: * *1* *121* *12321* *1234321* *123454321* *1234321* *12321* *121* *1* * Input: n = 3 Output: * *1* *121* *12321* *121* *1* * Approach: Two for loops will be run in this program in order to print the n
2 min read