At Westonci.ca, we make it easy for you to get the answers you need from a community of knowledgeable individuals. Explore our Q&A platform to find reliable answers from a wide range of experts in different fields. Explore comprehensive solutions to your questions from a wide range of professionals on our user-friendly platform.
Sagot :
Knuth-Morris-Pratt is more efficient string matches algorithm because doing less number of comparisons than its contraparte the brute force algorithm. The codes are shown below.
Brute Force algorithm
def BruteForce(p,s):
i = 0
j = 0
while(i < len(p) and j < len(s)):
if(p[i] == s[j]):
i += 1
j += 1
else:
i = i - j + 1
j = 0
if(j >= len(s)):
return i-len(s)
else:
return 0
if __name__ == "__main__":
string="gcagtacgcagagagtatacagtacg"
pattern='agtacg'
print("String: ", string)
print("Pattern: ", pattern)
ans=BruteForce(string,pattern)
print("Pattern found at index: ", ans)
Knuth-Morris-Pratt algorithm
def KnuthMorrisPratt(s,p):
if not p:
return 0
if not s or len(p) > len(s):
return 0
chars = list(p)
next = [0] * (len(p) + 1)
for i in range(1, len(p)):
j = next[i + 1]
while j > 0 and chars[j] is not chars[i]:
j = next[j]
if j > 0 or chars[j] == chars[i]:
next[i + 1] = j + 1
j = 0
for i in range(len(s)):
if j < len(p) and s[i] == p[j]:
j = j + 1
if j == len(p):
return i - j + 1
elif j > 0:
j = next[j]
i = i - 1
if __name__ == "__main__":
string="gcagtacgcagagagtatacagtacg"
pattern='agtacg'
print("String: ", string)
print("Pattern: ", pattern)
ans=KnuthMorrisPratt(string,pattern)
print("Pattern found at index: ", ans)
To learn more about string matches see: https://brainly.com/question/23095498
#SPJ4
![View image megatokay](https://us-static.z-dn.net/files/d07/619029648ed8d75011601e4c067db403.png)
![View image megatokay](https://us-static.z-dn.net/files/df6/2e4fcfe6af002606ebfced8d27adfd19.png)
Thanks for using our platform. We're always here to provide accurate and up-to-date answers to all your queries. We appreciate your time. Please revisit us for more reliable answers to any questions you may have. Westonci.ca is your go-to source for reliable answers. Return soon for more expert insights.