How to Implement LZ77 algorithm using Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to Implement LZ77 algorithm using Python?

How do I Implement LZ77 algorithm using Python giving that the text Sequence is input from the user with no restrictions on search window or look ahead window?

7th Nov 2022, 9:52 AM
Umar Shehu Usman
Umar Shehu Usman - avatar
2 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
11th Nov 2022, 9:22 AM
Doğu Aracı
+ 1
Thanks 🙏.
11th Nov 2022, 10:27 AM
Umar Shehu Usman
Umar Shehu Usman - avatar