pylcs - Longest Common Subsequence
pylcs is a Python library that provides a highly optimized C++ implementation of the Longest Common Subsequence (LCS) algorithm. It is currently at version 0.1.1 and offers a fast way to compute the length of the LCS between two strings. The project appears to have an infrequent release cadence, with the last update in late 2022.
Common errors
-
ModuleNotFoundError: No module named 'pylcs'
cause The 'pylcs' package is not installed in your current Python environment, or the installation failed.fixRun `pip install pylcs` to install the package. If it still fails, check for C++ compiler requirements. -
TypeError: lcs() takes exactly 2 arguments (1 given)
cause The `lcs` function was called with an incorrect number of arguments. It requires exactly two string arguments.fixEnsure you pass two string arguments to `lcs`, e.g., `lcs(string_a, string_b)`. -
TypeError: argument 1 must be str, not list
cause You attempted to pass a non-string type (e.g., a list, int, or dict) to the `lcs` function, which strictly expects string inputs.fixConvert all inputs to strings before calling `lcs`. For example, `lcs(str(my_list_item), str(my_other_item))`.
Warnings
- gotcha pylcs only returns the length of the LCS, not the actual subsequence itself. If you need the subsequence string, you'll need to implement or use another library's function for reconstruction.
- gotcha The library primarily accepts string inputs. Passing non-string types (e.g., lists, numbers) will result in a TypeError. Ensure both arguments passed to `lcs` are strings.
- gotcha As a C++ extension, installation of `pylcs` requires a C++ compiler (like GCC on Linux/macOS or MSVC on Windows) to be present and configured on your system. Installation might fail without it.
Install
-
pip install pylcs
Imports
- lcs
from pylcs import lcs
Quickstart
from pylcs import lcs
str1 = "ABCBDAB"
str2 = "BDCABA"
# Get the length of the longest common subsequence
lcs_length = lcs(str1, str2)
print(f"Strings: '{str1}', '{str2}'")
print(f"Length of LCS: {lcs_length}")
# Example with different strings
str3 = "AGGTAB"
str4 = "GXTXAYB"
print(f"\nStrings: '{str3}', '{str4}'")
print(f"Length of LCS: {lcs(str3, str4)}")