New course! Every coder should learn Generative AI!
Try a free lesson2 Answers
+ 1
Something like;
def lz77_encode(text, max_search, max_look_ahead):
# Initialize the output, the current position, and the longest match
output = []
current = 0
longest = 0
# Loop until the end of the text
while current < len(text):
# Set the search and look ahead windows
search = text[max(0, current - max_search) : current]
look_ahead = text[current : current + max_look_ahead]
# Initialize the best match
best_match = (0, 0, look_ahead[0])
# Loop through the search window
for i in range(len(search) - 1, -1, -1):
# Compare each character with the look ahead window
match = 0
while match < len(look_ahead) and search[i + match] == look_ahead[match]:
match += 1
# Update the best match if necessary
if match > best_match[1]:
best_match = (len(search) - i, match, look_ahead[match] if match < len(look_ahead) else '')
# Break the loop if the match is maximal
if match == len(look_ahead):
break
# Store the best match in the output
output.append(best_match)
# Update the current position and the longest match
current += best_match[1] + 1
longest = max(longest, best_match[1])
# Return the output and the longest match
return output, longest
+ 1
Thanks 🙏.