Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for LCS #1924

Merged
merged 1 commit into from
Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion redis/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import hashlib
import time
import warnings
from typing import List, Optional
from typing import List, Optional, Union

from redis.exceptions import ConnectionError, DataError, NoScriptError, RedisError

Expand Down Expand Up @@ -1857,6 +1857,35 @@ def unlink(self, *names):
"""
return self.execute_command("UNLINK", *names)

def lcs(
self,
key1: str,
key2: str,
len: Optional[bool] = False,
idx: Optional[bool] = False,
minmatchlen: Optional[int] = 0,
withmatchlen: Optional[bool] = False,
) -> Union[str, int, list]:
"""
Find the longest common subsequence between ``key1`` and ``key2``.
If ``len`` is true the length of the match will will be returned.
If ``idx`` is true the match position in each strings will be returned.
``minmatchlen`` restrict the list of matches to the ones of
the given ``minmatchlen``.
If ``withmatchlen`` the length of the match also will be returned.
For more information check https://redis.io/commands/lcs
"""
pieces = [key1, key2]
if len:
pieces.append("LEN")
if idx:
pieces.append("IDX")
if minmatchlen != 0:
pieces.extend(["MINMATCHLEN", minmatchlen])
if withmatchlen:
pieces.append("WITHMATCHLEN")
return self.execute_command("LCS", *pieces)


class ListCommands:
"""
Expand Down
11 changes: 11 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -954,6 +954,17 @@ def test_unlink_with_multiple_keys(self, r):
assert r.get("a") is None
assert r.get("b") is None

@pytest.mark.onlynoncluster
# @skip_if_server_version_lt("7.0.0") turn on after redis 7 release
def test_lcs(self, unstable_r):
unstable_r.mset({"foo": "ohmytext", "bar": "mynewtext"})
assert unstable_r.lcs("foo", "bar") == b"mytext"
chayim marked this conversation as resolved.
Show resolved Hide resolved
assert unstable_r.lcs("foo", "bar", len=True) == 6
result = [b"matches", [[[4, 7], [5, 8]]], b"len", 6]
assert unstable_r.lcs("foo", "bar", idx=True, minmatchlen=3) == result
with pytest.raises(redis.ResponseError):
assert unstable_r.lcs("foo", "bar", len=True, idx=True)

@skip_if_server_version_lt("2.6.0")
def test_dump_and_restore(self, r):
r["a"] = "foo"
Expand Down