Skip to content

Instantly share code, notes, and snippets.

@baryluk
Last active July 26, 2022 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baryluk/659df4a18cd01fb8db4c2d811d8cc97a to your computer and use it in GitHub Desktop.
Save baryluk/659df4a18cd01fb8db4c2d811d8cc97a to your computer and use it in GitHub Desktop.
Common prefix, suffix and two-sided compression
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