0
Finding short string in long string in Python3
Can someone please explain this algorithm to me? I put questionmarks behind the statements that I don't understand. a="string a" b="g" offset=0 N=len(a) M=len(b) found=False (?) while N-M >= offset and not found: (?) i=0 while i<M and a[i+offset]==b[i]: (?) i=i+1 if i>=M: found=True (?) else: offset=offset+1 if found: print("Found at",offset) else: print("Not found") I hope this is not too confusing.
3 Respuestas
+ 1
Found is of type bool and has been set false
As long as N (8) - M (1) is smaller as offset and found is not false not means opposite so its true
As long as i (0) is smaller than M (1) and a[i+offset (0)] """"if i is 0 its "(s)"""is equal to b [i] """if i is 0 its "(g)"""""
Set found to true
I hope its an understandable explanation and that i havent forgotten or interpreted anything wrong
0
I replaced the questionmarks with the comments
a="string a"
b="g"
offset=0
N=len(a)
M=len(b)
found=False #the var "found" is used to indiate, that the position of the short string is found (found == True)
while N-M >= offset and not found: # the loop ends in 2 cases: 1) the unexamened rest of the long string is shorter than the short string and so the first can not contain the last; 2) or the short string is found (found == True)
i=0
while i<M and a[i+offset]==b[i]: # the string b (the short one) is compared char by char with the part of the string a (the long one) beginning from the char number "offset"
i=i+1
...
0
...
if i>=M:
found=True # if i>=M (strictly saying if i ==M) the whole string b (all of its M symbols) is found in the string a
else:
offset=offset+1
if found:
print("Found at",offset)
else:
print("Not found")
So there are two loops. First loop goes throw string a from position 0 (offset ==0) to the pos.N-M. The second loop compares substring of string a, which starts from "offset", with the string b