I have homework that I cannot do correctly and not sure what's wrong with the code.
The exercise is : with simple search or Brute force find how many comparisons we make:
We have 2 lists that contain letters(string) and we compare them.Print out how many comparisons are made.
Example:
pattern= ABABC
text= ABBABACABCBAC
how I tried :
def search(text,pattern):
text=list(text)
pattern=list(pattern)
n=len(text)
m=len(pattern)
co=1
l=0
k=0
while k<=m:
if text[l] == pattern[k]:
co+=1
l+=1
k+=1
else:
co+=1
l+=1
k=0
c=co
return "Simple matching made " + str(c) +"
comparisons"
It should be 16, because we compare by letters and its like 3+1+1+4+1+2+1+3
We get 3 by: A=A means +1, B=B means 1,
B is not A so we add +1 but shift by one in the text.
I scripted something that does what I think you are looking for, but I think you are missing a term at the end unless I did it wrong. pattern = 'ABABC' text = 'ABBABACABCBAC'
def search(text, pattern):
slices = len(text) - len(pattern)
for i in range(0, slices + 1):
count = 0
text_to_compare = text[i:i + len(pattern)]
for j in range(len(pattern)):
count += 1
if pattern[j] == text_to_compare[j]:
continue
else:
break
print("{} -> {}".format(text_to_compare, count))
search(text, pattern)
This outputs
ABBAB -> 3
BBABA -> 1
BABAC -> 1
ABACA -> 4
BACAB -> 1
ACABC -> 2
CABCB -> 1
ABCBA -> 3
BCBAC -> 1
It can be adapted for total count like:
def search(text, pattern):
total_count = 0
slices = len(text) - len(pattern)
for i in range(0, slices + 1):
count = 0
text_to_compare = text[i:i + len(pattern)]
for j in range(len(pattern)):
count += 1
total_count += 1
if pattern[j] == text_to_compare[j]:
continue
else:
break
print("{} -> {}".format(text_to_compare, count))
print("Total count: {}".format(total_count))
Which outputs the same as before but also with:
Total count: 17
Is this what you are looking for? I can explain what parts you don't understand :)