I’m working in Python. I have the following code:
while not is_suffix(pattern[:k], pattern[:q]):
k -= 1
print k
def is_suffix(potential_suffix, text):
print "|" + potential_suffix + "|" + text + "|"
for i in range(len(text)):
if potential_suffix == text[i:]:
return True
return False
(The while loop is actually in a function, but I’ve omitted the non-relevant code). The result is that the while loop goes forever. The is_suffix function works when it can find two non-empty strings that are equal. However, in the case that I am having trouble with, it arrives at the end of the for loop and tries to compare text[i:] (which is empty) and potential_suffix, which is empty in this case. The code reaches the end and returns False, which causes the while loop to continue forever.
I claim that the two are empty strings because of the print line within is_suffix, which prints out “|||” in the relevant case.
Is there something fundamental I’m missing? Why would two empty strings not be considered equal?
The problem is that you never go through the
forloop iftext="". Then,len(text) == 0, andrange(0) == [], so there’s nothing to loop over. You probably want to either do an extra iteration of that loop:or explicitly check for an empty suffix:
at the beginning of the function.
However, you’re doing a lot of extra work in that function, since the loop is unnecessary. The following will do what you want: