Skip to content

Instantly share code, notes, and snippets.

@wecacuee
Created July 30, 2019 03:32
Show Gist options
  • Save wecacuee/1e4c9ea5f9baad9154d13aad06f19ce2 to your computer and use it in GitHub Desktop.
Save wecacuee/1e4c9ea5f9baad9154d13aad06f19ce2 to your computer and use it in GitHub Desktop.
Remove common parts and keep only the differences
def common_substr(strs, return_diffs=False):
"""
>>> common_substr("abcd", "xbcd")
'bcd'
"""
strs = list(strs)
min_len = min(map(len, strs))
max_len = max(map(len, strs))
first = strs[0]
comm = type(first)()
diffs = [type(first)() for s in strs]
for i in range(max_len):
if i < min_len and all((first[i] == s[i]) for s in strs):
comm.append(first[i])
else:
for d, s in zip(diffs, strs):
if i < len(s):
d.append(s[i])
return (comm, diffs) if return_diffs else comm
def diff_substr(strs, splitre="[-_/]", joinstr="-"):
comm, diffs = common_substr((re.split(splitre, s) for s in strs),
return_diffs=True)
return map(joinstr.join, diffs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment