Question

In: Computer Science

The Question is about Boyer-Moor-Horspool algorithm. I cannot set the code of pre-processing: initialization of shift...

The Question is about Boyer-Moor-Horspool algorithm.

I cannot set the code of pre-processing: initialization of shift table.

the Pseudocode is

1: for ? from 0 to |∑|– 1 do
2: ?[?] ← ?
3: for ? from 0 to ?– 2 do
4: ?[?[?]] ← ?– 1– ?
5: ? ← 0
6: while ? + ? ≤ ? do
7: ? ← ? - 1
8: while ?[? + ?] = ?[?] do
9: ? ← ? - 1
10: if ? < 0 then
11: return ?
12: ? ← ? + ?[?[? + ? - 1]]
13: return -1

so here is my code, but arise the error.|∑|– 1 : how can i express on python

def firstOccurrence(Text, Pattern):
T = len(Text)
P = len(Pattern)
if not isinstance(Text, str):
Text = Text.seq
Text = str(Text)
if not isinstance(Pattern, str):
Pattern = Pattern.seq
Pattern = str(Pattern)


S = {}
for k in range(0, P-1):
S[k] = P
for k in range(0, P-2):
S[Pattern[k]] = P-1-k

i = 0
while i + P <= T:
j = P -1
while Text[i+j] == Pattern[j]:
j -= 1
if j < 0:
return i
i += S[Text[i+P-1]]
return -1

print(firstOccurrence("ATTATTAAA", "AAA"))

>>Traceback (most recent call last): File , line 25, in firstOccurrence KeyError: 'T'

Solutions

Expert Solution

In the algorithm, they assume lookup table containing shifts for all possible (256) characters. This array is initialized to length of pattern . Then we scan the pattern and set the values of for all characters in .

In above algorithm, initialization is done in lines 1 and 2, whereas lines 3 and 4 are changing the values of   for all characters in .

In our python implementation, in order to avoid storage space wastage for characters not present in , we shall use a dictionary. In order to avoid ambiguity, we shall name the dictionary as . We skip initialization step, and directly set the values of for the characters that are present in .

While accessing the value for character in , we return if exists in . Or else, we use default value . In order to avoid key checking, python dict has a method get(), Using that, we can simplify the value access as - shift_table.get(c, m). Where m is the default value.

Now we shall proceed to code.

-- code start --

def firstOccurrence(Text, Pattern):
    n = len(Text)
    m = len(Pattern)
    # Shift table building phase
    S = {} # The shift table
    for k in range(0, m-2):
        S[Pattern[k]] = m-1-k
    i = 0
    while i + m <= n:
        j = m-1
        while Text[i+j] == Pattern[j]:
            j -= 1
        if j < 0:
            return i
        i += S.get(Text[i+m-1], m)
    return -1

if __name__ == '__main__':
    text = input("Enter text  : ")
    pattern = input("Enter pattern : ")
    print(" Text is ", text)
    print(" Pattern is ", pattern)
    print( "First occurance is " ,firstOccurrence(text, pattern))

-- code end --

Sample output:


Related Solutions

I am working with LCD HD44780 using pic18F1320. Can some provide me with the initialization code...
I am working with LCD HD44780 using pic18F1320. Can some provide me with the initialization code for LCD. Or the code I have to write to initializied LCD.
Hi, I have a question about the perceptual set. I have known what the perceptual set...
Hi, I have a question about the perceptual set. I have known what the perceptual set is, but I have no idea about is it better described as a kind of bottom-up processing or top-down processing? Please help me. I do highly appreciate your help. Regards,
I have to code the assignment below. I cannot get the program to work and I...
I have to code the assignment below. I cannot get the program to work and I am not sure what i am missing to get the code to work past the input of the two numbers from the user. My code is listed under the assignment details. Please help! Write a Java program that displays the prime numbers between A and B. Inputs: Prompt the user for the values A and B, which should be integers with B greater than...
Using the data set as a pre-defined variable in your program, write code that uses the...
Using the data set as a pre-defined variable in your program, write code that uses the dataset to print the first names of people who have BOTH above average math grades AND below average age from the dataset. The solutions for the textbook examples assume you are able to export in a framework like node.js, which is why in the data set I provide, I simply set the array of objects as a variable. Your code will be in the...
1. FLEXTIME, AS AN EMPLOYER, PRE COVID 19, THE QUESTION WAS "SHOULD I OR COULD I"  -...
1. FLEXTIME, AS AN EMPLOYER, PRE COVID 19, THE QUESTION WAS "SHOULD I OR COULD I"  - THE EMPLOYER HAD NO OBLIGATION OR REASON TO PROVIDE FLEXTIME OR TO EVEN CONSIDER IT IF IT WAS NOT TO THEIR LIKING - COVID 19 HAPPENS AND ALL OF A SUDDEN IT IS THE ONLY WAY TO STAY ALIVE AND HENCE THE REALITY OF SERVICE DELIVERY THROUGHOUT THE PANDAMIC - THOUGHTS / REFLECTIONS
I cannot get this code to run on my python compiler. It gives me an expected...
I cannot get this code to run on my python compiler. It gives me an expected an indent block message. I do not know what is going on. #ask why this is now happenning. (Create employee description) class employee: def__init__(self, name, employee_id, department, title): self.name = name self.employee_id = employee_id self.department = department self.title = title def __str__(self): return '{} , id={}, is in {} and is a {}.'.format(self.name, self.employee_id, self.department, self.title)    def main(): # Create employee list emp1...
in java: In my code at have my last two methods that I cannot exactly figure...
in java: In my code at have my last two methods that I cannot exactly figure out how to execute. I have too convert a Roman number to its decimal form for the case 3 switch. The two methods I cannot figure out are the public static int valueOf(int numeral) and public static int convertRomanNumber(int total, int length, String numeral). This is what my code looks like so far: public static void main(String[] args) { // TODO Auto-generated method stub...
I know this code takes in a set of numbers into a doubly linked list and...
I know this code takes in a set of numbers into a doubly linked list and sorts it using insertion sort. Could you explain exactly how this code is working? main.c Source Code: #include #include #include "node.h" int main() { struct mynode *head=NULL; int value; printf("Give first value: \n"); scanf("%d",&value); printf("Give next values, and input 0 to end list: \n"); do{ if(value>0){    head = pushNode(head, value);    scanf("%d",&value); } }while (value>0); printf("Before insertion sort: "); printlist(head); head=insertsort(head); printf("After insertion...
This is the HW question I cannot get the correct answer for. I've completed the first...
This is the HW question I cannot get the correct answer for. I've completed the first step but I cannot seem to get the correct numbers for EFN for 20, 25 and 30%!?!? See below for given financial statements and my table with the pro forma of 20, 25 and 30% numbers The most recent financial statements for Scott, Inc., appear below. Interest expense will remain constant; the tax rate and the dividend payout rate also will remain constant. Costs,...
Part four: using JDBC with mysql for project management program. I cannot copy the whole code,...
Part four: using JDBC with mysql for project management program. I cannot copy the whole code, so will split it into a few parts. See part one and two and three. Part four of The code is (starts at line 499, rest of code): } } catch (Exception e) { e.printStackTrace(); } if (foundSomething) { // pass } else { System.out.print("Search result is empty!\n"); } goBacktoMenu(); // go back to main menu } static void finalizeMenu(ArrayList<ProjectDetails> projectList) { System.out.print("========================Finalize project==========================\n\n");...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT