Last active
July 26, 2022 11:29
-
-
Save baryluk/659df4a18cd01fb8db4c2d811d8cc97a to your computer and use it in GitHub Desktop.
Common prefix, suffix and two-sided compression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def common_prefix(strings): | |
def _iter(): | |
for z in zip(*strings): | |
if z.count(z[0]) == len(z): # check all elements in `z` are the same | |
yield z[0] | |
else: | |
return | |
return "".join(_iter()) | |
def common_suffix(strings): | |
def _iter(): | |
for z in zip(*(reversed(s) for s in strings)): | |
if z.count(z[0]) == len(z): # check all elements in `z` are the same | |
yield z[0] | |
else: | |
return | |
return "".join(reversed(list(_iter()))) | |
def compress(strings, *, group_start="(", group_end=")", sep=","): | |
"""Given a list of strings, create a single string with prefix and suffix separated". | |
I.e. ["A_X_Z", "A_Y_Z"] -> "A_(X,Y)_Z" | |
""" | |
if len(strings) == 1: | |
return "".join(strings) | |
pre = common_prefix(strings) | |
suf = common_suffix(s[len(pre):] for s in strings) | |
return pre + group_start + sep.join(s[len(pre):].removesuffix(suf) for s in strings) + group_end + suf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment