Skip to content

Commit b1ffbc9

Browse files
authored
add support for lcs (#1924)
1 parent 9b99bf9 commit b1ffbc9

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

redis/commands/core.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1884,6 +1884,35 @@ def unlink(self, *names):
18841884
"""
18851885
return self.execute_command("UNLINK", *names)
18861886

1887+
def lcs(
1888+
self,
1889+
key1: str,
1890+
key2: str,
1891+
len: Optional[bool] = False,
1892+
idx: Optional[bool] = False,
1893+
minmatchlen: Optional[int] = 0,
1894+
withmatchlen: Optional[bool] = False,
1895+
) -> Union[str, int, list]:
1896+
"""
1897+
Find the longest common subsequence between ``key1`` and ``key2``.
1898+
If ``len`` is true the length of the match will will be returned.
1899+
If ``idx`` is true the match position in each strings will be returned.
1900+
``minmatchlen`` restrict the list of matches to the ones of
1901+
the given ``minmatchlen``.
1902+
If ``withmatchlen`` the length of the match also will be returned.
1903+
For more information check https://redis.io/commands/lcs
1904+
"""
1905+
pieces = [key1, key2]
1906+
if len:
1907+
pieces.append("LEN")
1908+
if idx:
1909+
pieces.append("IDX")
1910+
if minmatchlen != 0:
1911+
pieces.extend(["MINMATCHLEN", minmatchlen])
1912+
if withmatchlen:
1913+
pieces.append("WITHMATCHLEN")
1914+
return self.execute_command("LCS", *pieces)
1915+
18871916

18881917
class ListCommands:
18891918
"""

tests/test_commands.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -968,6 +968,17 @@ def test_unlink_with_multiple_keys(self, r):
968968
assert r.get("a") is None
969969
assert r.get("b") is None
970970

971+
@pytest.mark.onlynoncluster
972+
# @skip_if_server_version_lt("7.0.0") turn on after redis 7 release
973+
def test_lcs(self, unstable_r):
974+
unstable_r.mset({"foo": "ohmytext", "bar": "mynewtext"})
975+
assert unstable_r.lcs("foo", "bar") == b"mytext"
976+
assert unstable_r.lcs("foo", "bar", len=True) == 6
977+
result = [b"matches", [[[4, 7], [5, 8]]], b"len", 6]
978+
assert unstable_r.lcs("foo", "bar", idx=True, minmatchlen=3) == result
979+
with pytest.raises(redis.ResponseError):
980+
assert unstable_r.lcs("foo", "bar", len=True, idx=True)
981+
971982
@skip_if_server_version_lt("2.6.0")
972983
def test_dump_and_restore(self, r):
973984
r["a"] = "foo"

0 commit comments

Comments
 (0)